home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1992 June: ROMin Holiday / ADC Developer CD (1992-06) (''ROMin Holiday'')_iso / Developer Connection - 06-1992.iso / Developer Essentials / DTS Sample Code / Macintosh Sample Code / SC.024.SoundApp / SoundApp.p < prev    next >
Encoding:
Text File  |  1991-10-09  |  157.4 KB  |  4,093 lines  |  [TEXT/MPS ]

  1. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2. #
  3. # Apple Macintosh Developer Technical Support
  4. #
  5. # MultiFinder-Aware SoundApp Application
  6. #
  7. # SoundApp
  8. #
  9. # SoundApp.p - MPW 3.0/3.1 Pascal Source
  10. #
  11. # Jim Reekes - Macintosh Developer Technical Support
  12. # Copyright © 1989-1990 Apple Computer, Inc.
  13. # All rights reserved.
  14. #
  15. # Versions:
  16. #             1.03                    May, 1990
  17. #            1.04                    Sept, 1990
  18. #            1.1b1                    Nov, 1990            MPW 3.2 update
  19. #
  20. # Components:
  21. #             SoundApp.make        May, 1990            MPW build script
  22. #             SoundApp.p            May, 1990            Pascal source code
  23. #             SoundApp.r            May, 1990            Rez source code
  24. #             SoundAppSnds.r        May, 1990            Rez source code
  25. #             SoundUnit.p            May, 1990            Pascal source code
  26. #             Utilities.p            Nov, 1990            helpful routines from MacDTS
  27. #
  28. # Version comments
  29. #
  30. #    1.04: This was an update to support the Utilities Unit that MacDTS
  31. #    developed.  Some of it was routines formally created for SoundApp,
  32. #    with additional ones coming from other sources.  This helps to reduce
  33. #    the "destractive" code from the samples and makes them easier to maintain.
  34. #
  35. #    1.1:  This is the "new" SoundApp which adds some new features.
  36. #            • Some knowledge of the new Sound Manager is present
  37. #              in areas that were work-arounds for old Sound Manager bugs
  38. #            • Recording of sounds is now possible with the Sound Input Manager
  39. #            • The document window will keep the Record button hidden if
  40. #              the Sound Inpute Manager is not available for recording,
  41. #              otherwise it will expand the window size to show this button.
  42. #            • Supports copy and pasting of sound resources
  43. #            • Conversion to MPW 3.2 was established (with some amount of pain)
  44. #            • SoundApp now has its own documents
  45. #            • Supports launching by open documents from Finder
  46. #            • Added color icons for the System 7.0 desktop
  47. #            • Added the new Sound Manager error strings
  48. #            • DoErrorSound tests for safe beeps
  49. #            • Made Apple Legal happy by getting rid of the xxxxCmd
  50. #              and changed it to the freqDurationCmd.  Also got rid of
  51. #              any other use of the work "xxxx" in a musical context
  52. #
  53. #
  54. # Formatting was done with FONT = Monaco, SIZE = 9, TABS = 3
  55. #
  56. # many thanks to: Bo3b Johnson, Mark Bennett, Andy Shebanow, Keith
  57. # Rollin, Chris Derossi, Pete Helme, Darin Adler, and my co-workers that
  58. # sat near me while I was making lots of noise testing this application.
  59. #
  60. # To the reader,
  61. #
  62. # SoundApp.p is a sample application source file for demonstrating
  63. # the Sound Manager.  It requires the use of the SoundUnit to handle
  64. # all of the sound routines.  This portion of the source code handles the
  65. # application’s management of memory, errors, user interface, etc..
  66. # The read me notes are here in the source code because people tend to
  67. # not read them otherwise.
  68. #
  69. # SoundApp is a demonstration of the Sound Manager released in System
  70. # 6.0.x.  SoundApp is also a example of how to write a Macintosh
  71. # application that performs good user interface and proper error
  72. # handling.  Believe it or not, but the Sound Manager portion was the
  73. # easiest part for me to write.  It was all the user interface and error
  74. # handling that was the most difficult.  One thing became very clear to
  75. # me in the course of writing this application.  The following axiom is
  76. # one of the few great truths in the universe.
  77. #
  78. # If you write a Macintosh application without MacApp, you’re working
  79. # too hard.
  80. #
  81. # Throughout the development of SoundApp I would run into typical
  82. # situations that make programming a Macintosh too hard.  When this
  83. # happened I asked myself “what would MacApp do?” and that was followed
  84. # by the thought “then why am I writing code that is already out there
  85. # for me to use?”  I started out intending on writing a very simple
  86. # application that anyone could read, and understand the Sound Manager.
  87. # I felt this meant not requiring the person to read Object Oriented
  88. # Pascal.  I accomplished part of my goal.  People should be able to
  89. # learn how to use the Sound Manager (in its present condition), but it
  90. # didn’t turn out to be such a simple application as I had hoped for.
  91. #
  92. # I have put a large amount of comments into the code.  This is
  93. # something I’m really picky about.  People do not comment their code
  94. # enough.  Each procedure has a paragraph that should explain what to
  95. # expect that routine to do, and how it goes about doing it.  There are
  96. # some bigger issues that I will put into the release notes below.
  97. # There are some things that make the Macintosh harder to develop for
  98. # than it should be.  Simple things should be simple.  Too many things
  99. # on the Mac that should be simple are not.  Maybe someday these things
  100. # will be fixed.
  101. #
  102. # • GetFontInfo requires a port set to the font in question.  If I
  103. #   wanted to find the height of the System Font, I had to first set the
  104. #   current port to the WindowMgr.  I could have used my own window, but
  105. #   what if I needed the font info before I had a window available?
  106. # • The toolbox blows chunks when your heap gets “too low.”  I believe
  107. #   this magical number is between 32k and zero.  The odds of blowing
  108. #   chunks increase logarithmically as one approaches 0 free bytes.
  109. # • The Dialog Manager is not a free lunch and in fact will cost you
  110. #   plenty.
  111. # • There’s no safe way to determine how much memory opening a
  112. #   resource file will take away from your heap.
  113. # • There’s no way to determine how safe it is opening a resource that
  114. #   could be shared by other applications, especially on a local volume.
  115. # • The Resource Manager doesn’t always set ResErr.
  116. # • The Sound Manager returns even less errors.
  117. # • The List Manager returns no errors.
  118. # • Writing a staggering routine for new windows encompasses a number
  119. #   of difficulties.  How does one find the height of a window’s title
  120. #   region before the window is visible?
  121. #
  122. # Am I just a complainer?  Do I have a bad attitude?  Probably, but
  123. # I’m just trying to point out the above areas make the Mac programming
  124. # experience difficult.  These are areas that get developers into
  125. # trouble.  These areas need a sign in front of them that says,
  126. # “Danger!”  These are areas that developers get into and then write to
  127. # MacDTS for help.
  128. #
  129. # Notation Conventions
  130. # --------------------
  131. # All Pascal reserved words are in upper case.  All global variables
  132. # begin with a lower case “g”. All constants begin with “k” except for
  133. # those noted here.  Resource IDs begin with “r”.  Menu IDs being with
  134. # “m” and items with an “i”.  Resource strings begin with “s”.
  135. #
  136. # Human Interface
  137. # ---------------
  138. # This is the most important and about the most difficult aspect of
  139. # programming on the Macintosh.  In the development of SoundApp I gave much
  140. # thought to the human interface issues.  In fact, in talking with the Human
  141. # Interface Group additions to the existing guidelines were made.  The
  142. # method of window stacking used here was a new one.  This was documented in
  143. # a Human Interface Tech Note.  I even made one compromise (hard to
  144. # believe!) suggested by the Human Interface Group.  I originally had the
  145. # buttons and the list in my choice of font and size.  They felt that
  146. # buttons should be in the System font and the list should also be the same.
  147. # I liked my font choice better, but the group had a point that I really
  148. # couldn’t argue with.  That was, “If there isn’t a compelling reason to
  149. # change something standard, then don’t change it.”  Buttons on a Macintosh
  150. # typically appear in the System font.  Changing the font, just because I
  151. # wanted to, was considered gratuitous.  Standard File is in the System font
  152. # and it also contains a list and buttons.  Since my window are very similar
  153. # to that dialog, I’m using the System Font.
  154. #
  155. # SoundApp is never modal unless an error occurs and I need to show and
  156. # alert.  Controls are inactivated for inactive windows.  The default button
  157. # is given the proper outline, and this outline disappears when the window
  158. # is deactivated.  Keyboard equivalents for the buttons cause the button to
  159. # appear as if it had been clicked in.  The check box in the Standard File
  160. # dialog remembers the user’s last setting.  The about box is only
  161. # semi-modal.  It will allow the user access to switch to another application.
  162. # The status window under some circumstances was found to disappear too quickly,
  163. # so a built in delay was added.  Windows are centered or stacked according
  164. # to the Human Interface Guidelines.  The sound level isn’t adjusted by the
  165. # application, and instead the users is informed of the current level and
  166. # told how it can be adjusted.
  167. #
  168. # The About box
  169. # -------------
  170. # It’s rad.  Has a color icon, shows the 'vers' resource, goes Moof!™.  It
  171. # also demonstrates how to handle a modal window without the Dialog Manager.
  172. # This technique can be use for any window, including dialog windows.  The
  173. # dialog’s update routine would call UpdtDialog.  The really new point to
  174. # notice is this window is modal but ONLY within the application’s layer.
  175. # While running under MultiFinder, the user can switch to other
  176. # applications.  While the About window is present, it is the only window
  177. # belonging to the application that accepts user actions.
  178. #
  179. # Memory Management
  180. # ----------------
  181. # This has to be the most difficult portion of a Mac application to
  182. # write.  This along with the user interface.  I spent too many nights
  183. # chasing down crashes while running the application under low memory.
  184. # I found unpleasant surprises while doing this.  The Sound Manager
  185. # doesn’t check for NIL pointers.  OpenResFile may take large portions
  186. # of my heap away.  The toolbox seems to need at least 32k of free space
  187. # in the heap of my Mac II running color.
  188. #
  189. # I wrote a simple grow zone procedure that will dump a reserve memory
  190. # block.  This is only considered for use in an emergency.  I never rely
  191. # on using it directly.  If the reserve has been released, I will not
  192. # continue an operation such as playing a sound or showing the status
  193. # window until it is regained.  Grow zones should not be considered a
  194. # solution to memory management.  They can be used to augment your
  195. # overall memory management scheme.
  196. #
  197. # Error Checking
  198. # --------------
  199. # Lots and lots and lots of it.  I could even do more.  Programmers
  200. # need to do more of this.  The Sound Manager will crash when
  201. # encountering a NIL pointer.  My application should never crash.  If
  202. # you can find a way to crash this application, then I want to hear
  203. # about it.  Using a bogus 'snd ' resources doesn’t count and I’ve found
  204. # many of those.  Writing proper error checking into the code during
  205. # development really helped.  Always handle errors, and pass along the
  206. # error.  I will let the first error encountered to be passed all the
  207. # way up to the caller and eventually my error dialog will show up for
  208. # the user.
  209. #
  210. # SetPort Strategy
  211. # ----------------
  212. # Any routine that needs to use Quickdraw will set the port.  I do not
  213. # believe that it should also be responsible for restoring the port back
  214. # to what it may have been before the routine was called.  So, you’ll
  215. # find there is an absence of the GetPort, SetPort, do my thing, and
  216. # then SetPort again.  Instead I SetPort and do my thing.  The Mac often
  217. # is setting the port unnecessarily.
  218. #
  219. # Strings
  220. # -------
  221. # All of my strings are resources.  There are no strings that appear
  222. # within the code.  This helps memory management and allows me to adjust
  223. # the application to international systems without compiling any code.
  224. # I could simply use ResEdit, or some other tool, to localize this
  225. # application.  I find it is just as easy to run Rez again than
  226. # attempting to use ResEdit.  Besides, after editing with ResEdit I want
  227. # the source for that and would have to run DeRez which isn’t nearly as
  228. # clean as my original source files.
  229. #
  230. # Window Stacking
  231. # ---------------
  232. # I hate applications that will open a new document that covers up an
  233. # existing document, unless the new document covers the entire screen.
  234. # So, my application’s documents have a small window size.  I wanted to
  235. # open new windows that would not cover up older ones.  This is nice for
  236. # the user, since they will not have to move windows just to get at
  237. # other documents.  ResEdit will stagger new windows off of the
  238. # frontmost window but I find that this isn’t the best approach.  It
  239. # will still cover up other windows and I also don’t like windows that
  240. # will open half way between two monitors.  I wanted a better approach:
  241. # one that would always stagger new windows and not cover up older ones.
  242. #
  243. # When I want to center a window, I need to know its entire rectangle
  244. # size.  The rub is that I cannot determine its size until I show it
  245. # because I only know about the window’s boundsRect.  This does not
  246. # include the area that contains the title bar.  That’s the strucRgn,
  247. # which is an empty region for an invisible window.  I could do what
  248. # MacApp does, but if I have to do another thing that MacApp already
  249. # does I’ll give up and stick with MacApp.  I ended up writing a routine
  250. # that takes a guess at the height of the window’s title bar.  This is
  251. # another thing that was harder than it should have been.
  252. #
  253. # Dialog Manager (and some of the reasons I don’t like it)
  254. # --------------------------------------------------------
  255. # My first approach was to use modeless dialogs for document windows,
  256. # thinking that I could write an application that would demonstrate how to
  257. # deal with them and all of their idiosyncrasies.  Not long into the
  258. # development cycle it became obvious to me that I was fighting something
  259. # that contained more disadvantages than advantages.  I removed all the
  260. # dialog code and only used standard windows and controls the old fashion
  261. # way.  In the case of the About window, which is semi-modal, I have a test
  262. # that will return TRUE for a window that should be treated as modal.  This
  263. # allows my window to be handled by my standard event handlers and I don’t
  264. # have to write dialog filters.  There are some things that do not get
  265. # handled properly while calling ModalDialog.  ModalDialog ignores disk
  266. # insert events.  The activate or update events do not get handled for
  267. # background windows.  Using a modeless dialog fails with MultiFinder if
  268. # switching takes place while the dialog is the frontmost window.  The
  269. # problem is that DialogSelect ignores and removes the suspend/resume event.
  270. # Another advantage to all this is that drawing was much faster.
  271. #
  272. # As an example of some of the problems with ModalDialog and the activate
  273. # event.  Try this with the Finder.  Open a window and choose “View by name.”
  274. # Then select a few names with the shift key and resize the window so the
  275. # vertical scroll bar is visible.  Move this window to one edge of the
  276. # screen or a second monitor.  Now choose “Set Startup.”  This is a modal
  277. # dialog.  If you look at the Finder window with the selected files, you’ll
  278. # notice that the scrollbar and the text are still highlited.  This is not
  279. # the proper user interface.  This is because the deactivate routines are
  280. # not called while in ModalDialog.  You can even find this problem with
  281. # SoundApp.  On deactivate events I will change my controls to the inactive
  282. # state.  If you place the buttons to the side of the screen and then bring
  283. # up the standard file dialog, you’ll notice that the buttons don’t change
  284. # properly.  ModalDialog also prevents the application from updating
  285. # background windows too.  To solve this a dialog filter procedure is
  286. # required.  In most cases, this filter would be as complex and the event
  287. # loop.  It would also make it necessary to call your event routines from
  288. # outside of the normal event loop.  All on this isn’t worth the effort.
  289. #
  290. # You can see how this does not happen while using this application’s
  291. # About window.  Select an item in the document window and choose “Play
  292. # Melody.”  This will leave the status window on screen so that you can
  293. # drag it to cover the document window.  Now select “About SoundApp” to
  294. # bring up the about window.  This causes the status window to close,
  295. # which uncovers the document window leaving an invalid area.  The
  296. # document window gets an activate event, then the About window appears.
  297. # Then the document window is properly deactivated and updated.  Yeah,
  298. # just like it should happen.
  299. #
  300. # So, the tradeoff was that I didn’t have to work around all the
  301. # strange things the Dialog Manager does such as running a secondary
  302. # event loop, and requiring me to have userItems or filterProcs.  This
  303. # made the code smaller, more readable, and faster.  I think I will
  304. # avoid the Dialog Manger from now one unless I’m using a very simple
  305. # dialog.  The about window of this application proved too much for the
  306. # Dialog Manager.
  307. #
  308. # One thing dialogs are good for is running ResEdit and laying out the
  309. # dialog.  To help position controls, I used a DLOG resource of the same
  310. # size as my WIND resource.  The DITL of this dialog contains the
  311. # positions I wanted for my CNTL resources.  This helped me to look at
  312. # where I could expect my buttons to show up.  This is one of the main
  313. # reasons people think they need the Dialog Manager, because ResEdit
  314. # makes it easy to build dialogs.  ResEdit alone has contributed to
  315. # nearly all of the Dialog Manager abuse in the world today.
  316. #
  317. # I used a Rect resource for positioning the list rectangle of the
  318. # document windows.  These windows look very much like a modeless
  319. # dialog.  (They used to be, but that presented to many problems.)  The
  320. # About window is also a standard window, but shown modally.  Just like
  321. # ModalDialog, but my modal window does allow switching under
  322. # MultiFinder.  You can change the window to a dBoxProc and then
  323. # MultiFinder will not switch while this is the active window.  To help
  324. # with the layout of the about window, I position the text within it
  325. # based on the size of the window.  The status window does this too.
  326. # These two things, the Rect resource and text based on the size of the
  327. # window, help when changing the text.  If the new text doesn’t fit,
  328. # then resize the window’s resource.  I used some trick with Rez to help
  329. # layout my window contents.  Refer to the SoundApp.r sources.
  330. #
  331. # I’ve read and understood Tech Note #203, and have learned how to
  332. # apply it.  Bo3b Johnson is a smart guy, and developers should trust
  333. # his opinions.
  334. #
  335. # List Manager
  336. # ------------
  337. # It’s very easy to be tempted by this part of the toolbox, along with
  338. # the Dialog Manager.  The List Manager is a slow beast at times.  It
  339. # also has some problems with “doing the right thing.”  I’ve found that
  340. # the list will not be updated properly when the user clicks in a cell
  341. # that is out of bounds.  LClick will return TRUE with a cell that
  342. # doesn’t exists.  LActivate will erase the scrollbars instead of
  343. # highlighting the properly.  Finally, the List Manager does not return
  344. # errors.  How would a person know if LSetCell worked?
  345. #
  346. # I’ve read and understood Tech Note #203, and have learned how to
  347. # apply it.
  348. #
  349. # Resource Manager
  350. # ----------------
  351. # I test all the handles being returned from the Resource Manager
  352. # before using them, and if I get a NIL then I look at ResError.
  353. # ResError sometimes lies and returns noErr and a NIL handle.  ResError
  354. # is usually good for getting an error code AFTER you’ve already found
  355. # an error.
  356. #
  357. # Opening a resource file that is already open by another application
  358. # is dangerous.  The Resource Manager will not tell you when you’ve done
  359. # this.  There needs to be a OpenRFPerm that will return permission
  360. # errors such as resFileBusyErr.  Refer to Tech Note #185.
  361. #
  362. # When I or the Toolbox needs to get at one of my resources,
  363. # CurResFile must be set to my application.  Also, look out for one
  364. # particularly nasty situation when switching resource files.   If the
  365. # segment loader goes for a CODE segment, it better be from our resource
  366. # file!  The idea here is, in case you didn’t get it already, always
  367. # have the current resource file be set to the application.  If a
  368. # resource is needed from another file, switch momentarily to get the
  369. # resource and immediately restore the current resource file to the
  370. # application.  I take an added measure of defense and whenever I need a
  371. # resource I use the Get1Resource calls.  These will only search the
  372. # current resource file.
  373. #
  374. # Strategies For Sound
  375. # --------------------
  376. # All of the Sound Manager code is contained in the SoundUnit.p.  This
  377. # unit was written to be general purpose, providing useful routines for
  378. # other applications.  Lots of error checking is performed.  I’ve also
  379. # extended the support for SndPlay and made it really asynchronous.
  380. # I’ve demonstrated most of the abilities the present Sound Manager has
  381. # to offer.  I will have to revise the SoundAppUnit to include any new
  382. # features (e.g., multi channel support) when the next Sound Manager is
  383. # released.
  384. #
  385. # I allocate my own memory to be used as sound channels.  I allocate
  386. # these pointers early in the application’s startup time to avoid memory
  387. # fragmentation.  These channels are of the standard size (holding 128
  388. # commands) but I’ve extended the structure to include my own
  389. # information.  When I create a new sound channel, I pass it a pointer
  390. # to this memory.  This will link in the 'snth' resource and hardware to
  391. # my channel.  When I dispose of the channel, the Sound Manager will
  392. # purge this resource and disconnect me from the hardware.  When adding
  393. # the 'snth' resource, the Sound Manager will allocate a pointer into
  394. # the application’s heap instead of the system’s.  This is a modifier
  395. # stub used by the 'snth'.  This could cause some problems with memory
  396. # management.  I create and dispose of all my channels as soon as
  397. # possible, and this doesn’t cause me problems.
  398. #
  399. # I keep track of which document is playing a sound, along with a
  400. # global of when the application is playing sound.  I needed to keep
  401. # track of which document is playing because if the user disposes of
  402. # that document, I will have to stop playing the sound contained in it
  403. # since the user wants to dispose of that data.  I keep track of when
  404. # the application is playing sound in a global.  This is only used by
  405. # the routine that calculates the sleep time for WaitNextEvent.
  406. #
  407. # I came up with a pretty sick music notational system using Rez.
  408. # Refer to the notes in the SoundAppSnds.r file.  If you’ve just
  409. # finished a meal, wait four hours before reading.
  410. #
  411. # The SoundUnit handles all of the Sound Manager code entirely.  This
  412. # eliminates any and all references to the Sound Manager from the
  413. # application.  The SoundUnit will return any error encountered while
  414. # calling the Sound Manager, and does some extra error checking the
  415. # Sound Manager doesn’t do.
  416. #
  417. # The portion of the application that uses the wave table synthesizer
  418. # is more complex than the other two.  I wanted to include an example
  419. # channel modifier for use in the wave table channels.  This would have
  420. # been a transpositional modifier that would take a given freqDurationCmd and
  421. # transpose it by some amount.  This would be nice for the routine that
  422. # plays a scale, by allowing the other three channels to be playing the
  423. # same scale but at a different interval.  Unfortunately, I found that
  424. # the Sound Manager has bugs using a modifier, at least with the wave
  425. # table synths, and could not use them.
  426. #
  427. # I’ve created a few wave table sounds and keep them in a 'snd '
  428. # resource.  This allows me to change the sound of the wave table
  429. # channels and not change any of the code.  Creating wave table data is
  430. # complicated.  The example sounds I’ve included are samples I’ve taken
  431. # from various sources.  I’ve cleaned them up quit a bit.  This was to
  432. # set loop points, try and reduce clicks, correct the sample rates, and
  433. # base frequencies.  This is also a complicated task.  Maybe I should document
  434. # these techniques.
  435. #
  436. # Jim Reekes E.O., Macintosh Developer Technical Support
  437. # Tuesday, January 30, 1990  1:01 PM
  438. #
  439. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  440.  
  441. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  442. PROGRAM SoundApp;
  443. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  444.  
  445. {I’m purposely avoiding the use of the interface files OSIntF and PackIntf.
  446.  These two files include lots of others, some of which I don’t need.
  447.  By avoiding the use of these files, compile times are faster.  It helps
  448.  cut down on the symbol table thrashing by loading unnecessary files.
  449.  Anything to help MPW go faster!  I could also avoid ToolIntf, but in my
  450.  application I’m using all of the files it includes.}
  451.  
  452. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  453. USES
  454. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  455.     Types, QuickDraw, Traps, ToolIntf, Files, SegLoad, Packages, Menus,
  456.     OSEvents, DiskInit, SysEqu, Script, Errors, CursorCtl, Sound, SoundInput,
  457.     SoundUnit;
  458.  
  459. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  460. CONST
  461. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  462.     kSysEnvironsVersion =    1;        {Version of the SysEnvRec I understand.}
  463.     kSystem602 =            $0602;    {SysEnvRec value for System version 6.0.2}
  464.     kPollingSleepTime =    60;        {MultiFinder’s sleep while sound is playing}
  465.  
  466.     kNumberOfMasters =     3;            {number of master pointer blocks we expect}
  467.     kSizeOfReserve =        32 * 1024; {size of reserve memory for grow zone proc}
  468.     kMinSpace =                32 * 1024; {minimum available memory I allow in heap}
  469.     kMemForSndDoc =        20 * 1024; {minimal amount of memory needed by document}
  470.  
  471.     rAppSignature =         'SAPP';    {applicaiton’s OS signature}
  472.     rSndAppDocType =        'sDoc';    {document's file type}
  473.     
  474.     kScrollBarAdjust =    15;        {the width of the scrollbar in the list}
  475.     kListFrameInset =        -1;        {inset rectangle adjustment for list frame}
  476.     kMsgInset  =            8;            {inset rectangle adjustment for messages}
  477.  
  478.     kSFTopLeft =            $00280032; {40,50 is topLeft for Std File dialog}
  479.  
  480.     kCntlActivate =        0;            {enabled control’s hilite state}
  481.     kCntlDeactivate =        255;        {disabled control’s hilite state}
  482.     kSelect =                1;            {select the control}
  483.     kDeselect =                0;            {deselect the control}
  484.     kCntlOn =                1;            {control’s value when truned on}
  485.     kCntlOff =                0;            {control’s value when truned off}
  486.  
  487.     kButtonFrameSize =    3;            {button’s frame pen size}
  488.     kButtonFrameInset =    -4;        {inset rectangle adjustment around button}
  489.     kButtonSizeH =            17;        {standard height of buttons}
  490.     kDafaultButSizeH =     kButtonSizeH - kButtonFrameInset - kButtonFrameInset;
  491.  
  492.  
  493. {refer to the SoundApp.r file for the explaination about these numbers}
  494.     kNumOfButtons =        6;            {the number of buttons in the window}
  495.     kSndStdSpacing =        8;            {adjusts relative spacing of the entire window}
  496.     kSndButtonSizeW =        100;        {SizeW of buttons in document window}
  497.     kSndButtonSizeH =        24;        {heigth of buttons in document window}
  498.     kSoundWindowSizeH =    ((kNumOfButtons * kSndStdSpacing)
  499.                                  + (kNumOfButtons * kSndButtonSizeH) + kSndStdSpacing);
  500.     kSoundWindowSizeW =    296;
  501.  
  502.     kIconTop =                10;        {standard position for icons in alerts}
  503.     kIconLeft =                20;
  504.     kIconBot =                42;
  505.     kIconRight =            52;
  506.     kIconPictGap =            8;            {pict spacing in about window}
  507.  
  508.     kFSAsynch =                TRUE;        {asynchronous File Manager call}
  509.  
  510.     kEnterKey =                CHR($03); {the keys I’m looking for}
  511.     kReturnKey =            CHR($0D);
  512.     kEscape =                CHR($1B);
  513.     kUpArrow =                CHR($1E);
  514.     kDownArrow =            CHR($1F);
  515.     kPeriod =                CHR($2E);
  516.     kBackspace =            CHR($08);
  517.     kDelete =                CHR($7F);
  518.  
  519. {This bit set in the ioFlAttrib field if the file’s resource fork is open.}
  520.     kResForkOpenBit =        2;
  521.  
  522. {For the delay time when flashing the menubar and highlighting a button.}
  523.     kDelayTime =            8;            {8/60ths of a second}
  524.  
  525. {The lowest volume I consider before suggesting the user increase it.}
  526.     kMinVolumeDesired =    4;
  527.  
  528. {The minimal number of ticks the ShowWindow needs to be visible.}
  529.     kShowTimeDelay    =        20;
  530.  
  531. {BUG NOTE: Using a timbre value of 255 on the Mac Plus/SE will cause a crash.}
  532.     kSquareWave =            240;         {square wave for squareWaveSynth}
  533.     kSineWave =                0;            {sine wave for the squareWaveSynth}
  534.     kPreferredTimbre =    190;        {my preferred timbre for the squareWaveSynth}
  535.   
  536. {Application snd resources must be higher than this number.}
  537.     kSystemSndRange =     8191;        {This is the highest snd id reserved by Apple.}
  538.  
  539. {The following constants are the resource IDs.}
  540.     rMenuBar =                1000;        {application’s menu bar}
  541.  
  542.     rExitAlert =            1000;        {emergency exit user alert}
  543.     rUserAlert =            1001;        {error message user alert}
  544.     rSoundVolAlert =        1002;        {sound is set low alert}
  545.     rSaveAlert =             1003;        {save changes? dialog}
  546.  
  547.     rGetNameDLOG =         1000;        {get a name for the sound dialog}
  548.     rNameItem =                3;            {edit text item in rGetNameDLOG}
  549.     rUserItem =             5;            {user item to help draw default outline}
  550.     
  551.     rSFPGetFileDLOG =        -4000;    {dialog template for SFPGetFile}
  552.     rSndOnlyCheckBox =    11;        {dialog item number in SFPGetFile}
  553.  
  554. {These are the window IDs used in the applications.  Each one must be unique,
  555.  since they are used to identify which window the event took place in.}
  556.     rAboutWindow =            1000;        {about window}
  557.     rStatusWindow =        1001;        {sound status window}
  558.     rSoundWindow =            1002;        {sound document window}
  559.  
  560.     rListRectID =            1000;        {resource containing size of list rectangle}
  561.  
  562.     rCancelCntl =            1000;        {stop button ID for the status window}
  563.     rPlaySndCntl =            1001;        {sound button IDs for the sound document window}
  564.     rHyperPlayCntl =        1002;
  565.     rPlayScaleCntl =        1003;
  566.     rMelodyCntl =            1004;
  567.     rStopCntl =                1005;
  568.     rRecordCntl =             1006;
  569.     rAboutOkCntl =            1007;
  570.     rUntitled =                1000;        {string ID for untitled resources}
  571.     rAboutText =            1001;        {string ID for text appearing in about window}
  572.     rPutFileMsg =             1002;        {string for text appearing in SFPutFile dialog}
  573.     rMoofIcon =                1000;        {resource ID for ICON of application}
  574.     rAppPict =                1000;        {resource ID of picture shown in about window}
  575.     rSndCursor =            1000;        {cursor resource for our documents}
  576.  
  577. {The following are the snd resource IDs contained in the application,
  578.  which start at ID 9000.  IDs 0 - 8191 are reserved for Apple.}
  579.     rMoofSound =            9000;        {snd for the about window}
  580.     rScaleSnd =                9001;        {snd containing a scale}
  581.     rMelodyPart1 =            9002;        {snd containing a melody}
  582.     rMelodyPart2 =            9003;        {snd containing the harmony}
  583.     rMelodyPart3 =            9004;        {snd containing the harmony}
  584.     rMelodyPart4 =            9005;        {snd containing the harmony}
  585.     rWaveHarmony =         9006;        {snd containing waveTable for harmony}
  586.     rWaveMelody =             9007;        {snd containing waveTable for melody}
  587.     rCounterPt1    =            9008;        {snd containing soprano part of counter point}
  588.     rCounterPt2 =            9009;        {snd containing alto part of counter point}
  589.     rCounterPt3 =            9010;        {snd containing tenor part of counter point}
  590.     rCounterPt4 =            9011;        {snd containing bass part of counter point}
  591.     rSopranoVox =             9012;        {snd containing waveTable of soprano voice}
  592.     rAltoVox =                9013;        {snd containing waveTable of alto voice}
  593.     rTenorVox =                9014;        {snd containing waveTable of tenor voice}
  594.     rBassVox =                9015;        {snd containing waveTable of bass voice}
  595.  
  596. {The following are resource IDs for messages.}
  597.     sErrStrings =            1000;        {error string STR# ID}
  598.     sStandardErr =            1;            {An error has occurred.}
  599.     sMemErr =                2;            {A Memory Manager error has occurred.}
  600.     sResErr =                3;            {A Resource Manager error has occurred.}
  601.     sCurInUseErr =            4;            {That file is currently in use.}
  602.     sWavesBroken =            5;            {The wave table synthesizer is not available.}
  603.     sWrongVersion =        6;            {This system does not support the Sound Manager...}
  604.     sLowMemory =            7;            {Memory is too low to continue...}
  605.     sNoMenus =                8;            {Could not find application’s menu resources.}
  606.     sInitSoundErr =        9;            {Could not initialize the Sound unit.}
  607.     sSoundErr =                10;        {The Sound Manager has encountered an error.}
  608.     sNewDocErr =            11;        {Could not create a new document.}
  609.     sInitStatusErr =        12;        {Error initializing the status window.}
  610.     sEditErr =                13;        {Could not complete the edit command.}
  611.     sDocErr =                14;        {There is a problem with this document.}
  612.  
  613.     sMsgStrings =            1001;        {message string STR# ID}
  614.     sPlayingMsg =            1;            {playing a sound}
  615.     sHyperMsg =                2;            {playing a sound the Hyper way}
  616.     sScaleMsg =                3;            {playing scale}
  617.     sMelodyMsg =            4;            {playing melody}
  618.     sTimbresMsg =            5;            {playing various timbres}
  619.     sCounterPtMsg =        6;            {playing 4 part counter point}
  620.  
  621.     sSMErrStrings =        1002;        {strings describing Sound Manager errors}
  622.  
  623. {The following constants are used to identify menus and items. The menu IDs
  624.  have an “m” prefix and the item numbers within each menu have an “i” prefix.}
  625.     mApple =                    128;        {Apple menu and items}
  626.     iAbout =                    1;
  627.  
  628.     mFile =                    129;        {File menu and items}
  629.     iNew =                    1;
  630.     iOpen =                    2;
  631.     iClose =                    4;
  632.     iQuit =                    12;
  633.  
  634.     mEdit =                    130;        {Edit menu and items}
  635.     iUndo =                    1;
  636.     iCut =                    3;
  637.     iCopy =                    4;
  638.     iPaste =                    5;
  639.     iClear =                    6;
  640.  
  641.     mDemos =                1000;            {Demos menu and items}
  642.     iSquareScale =            1;
  643.     iSquareMelody =        2;
  644.     iSquareTimbre =        3;
  645.     iWaveScale =            5;
  646.     iWaveMelody =            6;
  647.     iWaveSATB =                7;
  648.  
  649. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  650. TYPE
  651. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  652.  
  653.     BooleanPtr =        ^BOOLEAN;            {Ptr to a BOOLEAN, for type coercion}
  654. {    IntegerPtr =        ^INTEGER;            Ptr to a INTEGER, for type coercion}
  655. {    LongIntPtr =        ^LongInt;            Ptr to a LONGINT, for type coercion}
  656. {    RectPtr =            ^Rect;                Ptr to a Rect resource for coercion}
  657.     RectHandle =        ^RectPtr;            {Handle to a Rect resource for coercion}
  658.  
  659. {This is a document layout that contains the window record and references
  660.  to the associating data.  The window record MUST be the first field.  This
  661.  is because I use the window pointer returned by the Toolbox to be a
  662.  pointer to my document.  To confirm that the window pointer is a document
  663.  pointer, I store an application reference in the window record’s refCon.
  664.  Then, I use a routine to test for the presence of this reference to insure
  665.  I’m looking at one of my document’s windows.}
  666.  
  667.     SndDocument =     RECORD
  668.         window:        WindowRecord;            {must be first field}
  669.         resFile:        INTEGER;                    {document’s resource file}
  670.         vRefNum:        INTEGER;                    {real volume that contains the doc}
  671.         dirID:        LONGINT;                    {the dirID that contains the doc}
  672.         list:            ListHandle;                {document’s list of sounds}
  673.         sndInUse:    BOOLEAN;                    {document is using a 'snd ' resource}
  674.     END;
  675.     SndDocPeek =    ^SndDocument;            {to peek at the document record}
  676.  
  677. {This is the status window layout.  The concept here is similar to the
  678.  document type mentioned above.  The message is a string handle used to
  679.  store the current message.}
  680.  
  681.     StatusWindow = RECORD
  682.         window:        WindowRecord;
  683.         message:        StringHandle;            {current text of status message}
  684.         showTime:    LONGINT;                    {time window was shown}
  685.     END;
  686.     StatWindowPeek = ^StatusWindow;
  687.  
  688. {This is the about window layout.  The concept here is similar to the
  689.  document type mentioned above.  The comment is a string handle used to
  690.  store the current message.}
  691.  
  692.     AboutWindow =    RECORD
  693.         window:        WindowRecord;
  694.         comment:        Handle;                    {handle to string of about comments}
  695.         appIcon:        Handle;                    {handle to icon or color icon}
  696.         iconIsColor:Boolean;                    {TRUE if above icon is color}
  697.         appPict:        Handle;                    {handle to picture of app’s name}
  698.     END;
  699.     AboutWPeek =    ^AboutWindow;
  700.  
  701. {This is the template to the WIND resource.  I used it to load in the WIND
  702.  resource and then adjust the boundsRect.  I also look at the procID to
  703.  determine if it has a title bar or drag region.}
  704.  
  705.     WindowTemplate =    RECORD                {template to a WIND resource}
  706.         boundsRect:    Rect;
  707.         procID:        INTEGER;
  708.         visible:     BOOLEAN;
  709.         filler1:     BOOLEAN;
  710.         goAwayFlag: BOOLEAN;
  711.         filler2:     BOOLEAN;
  712.         refCon:        LongInt;
  713.         title:        Str255;
  714.     END;
  715.     WindowTPtr =    ^WindowTemplate;
  716.     WindowTHndl =    ^WindowTPtr;
  717.  
  718. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  719. VAR {The “g” prefix is used to emphasize that a variable is global.}
  720. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  721.  
  722. {gMac is used to hold the result of a SysEnvirons call. This makes it
  723.  convenient for any routine to check the environment. It is considered
  724.  global information, anyway.}
  725.  
  726.     gMac:                        SysEnvRec;        {set up by Initialize}
  727.  
  728. {gReserveMemory is a handle of reserve memory used by my grow zone
  729.  procedure.  If memory is attempted to be allocated and fails, my grow
  730.  zone will release this reserved block of memory.}
  731.  
  732.     gReserveMemory:        Handle;
  733.  
  734. {gStatusWindow is the window that tells the user what’s happening.  I show
  735.  it while a sound is playing, and remove it as soon as the sound is
  736.  complete.  It is initialized once during startup, and from then on two
  737.  routines are used to show and hide it.  This demonstrates orchestrating
  738.  multimedia, that sound/graphic idea, at least in a crude sort of way.}
  739.  
  740.     gStatusWindow:            StatWindowPeek;
  741.  
  742. {gAppResRef is the application’s resource file reference.  I need to save
  743.  this since I can open other resource files.  The current resource file is
  744.  always gAppResRef unless I momentarily set it to another file to read its
  745.  resources, and then immediately restore it back.}
  746.  
  747.     gAppResRef:             INTEGER;            {set up by Initialize}
  748.  
  749. {gInBackground is maintained by our osEvent handling routines. Any part of
  750.  the program can check it to find out if it is currently in the background.}
  751.  
  752.     gInBackground:         BOOLEAN;            {maintained by Initialize and DoEvent}
  753.  
  754. {gSndFilesOnly is used to determine if the check box in the custom
  755.  SFPGetFile dialog has been chosen.  If this is true, then I want to only
  756.  show files that contain 'snd ' resources.}
  757.  
  758.     gSndFilesOnly:            BOOLEAN;            {maintained by SFGetHook}
  759.  
  760.  
  761. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  762. { IMPLEMENTATION }
  763. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  764. {$S Main}
  765. FUNCTION MyGrowZone(cbNeeded: Size): LONGINT;
  766.  
  767. {This is a very basic grow zone procedure.  My application keeps a reserve
  768.  handle of memory in case the Memory Manager gets a request for some memory
  769.  that is not available in my heap.  If memory were to get tight (<32k),
  770.  the Toolbox will crash the system, especially Quickdraw.  Before releasing
  771.  the reserve handle I make sure it isn’t the GZSaveHnd.  This handle cannot
  772.  be touched by the grow zone procedure.
  773.  
  774.  WARNING:  The grow zone procedure will be called and A5 may not be valid.
  775.  Read Tech Note #136 and 208}
  776.  
  777. VAR
  778.     theA5:         LONGINT;
  779.  
  780. BEGIN
  781.     theA5:= SetCurrentA5;
  782.     IF (gReserveMemory^ <> NIL) & (gReserveMemory <> GZSaveHnd) THEN BEGIN
  783.         EmptyHandle(gReserveMemory);
  784.         MyGrowZone:= kSizeOfReserve;                {released this much memory}
  785.     END ELSE
  786.         MyGrowZone:= 0;                                {this may release more memory}
  787.     theA5:= SetA5(theA5);
  788. END; {MyGrowZone}
  789.  
  790. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  791. {$S Main}
  792. FUNCTION LowOnReserve: BOOLEAN;
  793.  
  794. VAR
  795.     total, contig:            LONGINT;
  796.  
  797. {Before my application attempts to use more memory, I call this routine
  798.  to check if I’m already using my reserve memory.  If so, then I better
  799.  prepare to die or get my reserve back.}
  800.  
  801. BEGIN
  802.     LowOnReserve:= gReserveMemory^ = NIL;        {empty handle is low reserve}
  803. END; {LowOnReserve}
  804.  
  805. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  806. {$S Main}
  807. PROCEDURE RecoverReserve;
  808.  
  809. {This is called from the event loop if LowOnReserve returns that I’m out of
  810.  the reserve memory.  This will recover the reserve memory block.  If this
  811.  fails, it will be called the next time through the event loop.}
  812.  
  813. BEGIN
  814.     ReallocHandle(gReserveMemory, kSizeOfReserve);
  815. END; {RecoverReserve}
  816.  
  817. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  818. {$S Initialization}
  819. FUNCTION AllocateReserve: BOOLEAN;
  820.  
  821. {This is called at startup time to allocate the reserve memory block used
  822.  in the grow zone procedure.  If I’m unable to obtain this reserve, then
  823.  return FALSE to signal a failure.}
  824.  
  825. BEGIN
  826.     gReserveMemory:= NewHandle(kSizeOfReserve);
  827.     AllocateReserve:= gReserveMemory <> NIL;
  828. END; {AllocateReserve}
  829.  
  830. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  831. {$S Main}
  832. FUNCTION FailLowMemory(memRequest: LONGINT): BOOLEAN;
  833.  
  834. {Call PurgeSpace and see if the requested amount of memory exists in the
  835.  heap including a minimal amount of heap space.  Also, if my grow zone’s
  836.  reserve has been release, that’s considered a failure.  I don’t perform
  837.  any purging here.  The Memory Manager will do this if it needs the space.
  838.  This routine can be called with a memRequest = 0.  This checks if the heap
  839.  space is getting critical.}
  840.  
  841. VAR
  842.     total, contig:        LONGINT;
  843.  
  844. BEGIN
  845.     PurgeSpace(total, contig);
  846.     FailLowMemory:= (total < (memRequest + kMinSpace)) | LowOnReserve;
  847. END; {FailLowMemory}
  848.  
  849. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  850. {$S Main}
  851. FUNCTION HasSelection(sndDoc: SndDocPeek): BOOLEAN;
  852.  
  853. {This a simple test to see if the user has a currently selected list item.}
  854.  
  855. VAR
  856.     aCell:            Cell;
  857.  
  858. BEGIN
  859.     SetPt(aCell, 0, 0);
  860.     HasSelection:= LGetSelect(TRUE, aCell, sndDoc^.list)
  861. END; {HasSelection}
  862.  
  863. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  864. {$S Main}
  865. FUNCTION GetSelection(sndDoc: SndDocPeek; VAR sndHandle: Handle): OSErr;
  866.  
  867. {Given a document, this will find the currently selected cell in the list.
  868.  Then using this cell as an index number, I call Get1IndResource.  This
  869.  will return the proper handle.  Since the List Manager is zero based and
  870.  the Resource Manager isn’t, I have to add one to the index.
  871.  
  872.  BUG NOTE: GetIndResource will return a bogus handle if the index is not
  873.  positive.}
  874.  
  875. VAR
  876.     aCell:             Cell;
  877.  
  878. BEGIN
  879.     GetSelection:= noErr;
  880.     SetPt(aCell, 0, 0);
  881.     IF LGetSelect(TRUE, aCell, sndDoc^.list) THEN BEGIN
  882.         IF aCell.v > -1 THEN BEGIN                {GetIndResource doesn’t like < 0}
  883.             UseResFile(sndDoc^.resFile);        {only get our resources}
  884.             sndHandle:= Get1IndResource('snd ', aCell.v + 1);
  885.             IF sndHandle = NIL THEN
  886.                 GetSelection:= ResError;        {return any error}
  887.             UseResFile(gAppResRef);                {restore our resource file}
  888.         END;
  889.     END;
  890. END; {GetSelection}
  891.  
  892. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  893. {$S Main}
  894. PROCEDURE SelectNextCell(list: ListHandle; next: BOOLEAN);
  895.  
  896. {This is used to allow the user to select items from the list by using
  897.  the arrow keys.  Given a list and the direction, this will select the
  898.  next cell.  It will do nothing if we’re at the first cell and the user
  899.  wants to do even higher (sped), or if we’re at the last cell and the
  900.  user wants to go even lower (rent a clue bud).}
  901.  
  902. VAR
  903.     aCell:            Cell;
  904.     lastItem:        INTEGER;
  905.  
  906.     PROCEDURE DoNextSelection;
  907.     BEGIN
  908.         LSetSelect(FALSE, aCell, list);
  909.         IF next THEN
  910.             aCell.v:= aCell.v + 1
  911.         ELSE
  912.             aCell.v:= aCell.v - 1;
  913.         SetPt(aCell, aCell.h, aCell.v);
  914.         LSetSelect(TRUE, aCell, list);
  915.         LAutoScroll(list);
  916.     END;
  917.  
  918. BEGIN
  919.     lastItem:= list^^.dataBounds.bottom - 1;        {bounds is 1 greater}
  920.     SetPt(aCell, 0, 0);
  921.     IF LGetSelect(TRUE, aCell, list) THEN BEGIN
  922.         IF (next & (aCell.v < lastItem)) | ((NOT next) & (aCell.v > 0)) THEN
  923.             DoNextSelection;
  924.     END ELSE                                                    {if no cells selected...}
  925.         LSetSelect(TRUE, aCell, list);                {select the first cell}
  926. END; {SelectNextCell}
  927.  
  928. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  929. {$S Main}
  930. PROCEDURE SelectSndCell(sndDoc: SndDocPeek; resID: INTEGER);
  931.  
  932. {VERSION 1.1:  This routine will go through the list of snd resources  
  933.  looking for the one that has the resource ID matching the parameter passed   
  934.  in.  First thing to do is deselect the current selection.  Then once the  
  935.  matching resource is found, select that one and scroll it into view.  One  
  936.  assumption made is that the resources and the list are both index in the   
  937.  same order.  This is true for the sndDoc, since I built the list this way.}
  938.  
  939. VAR
  940.     name:                    Str255;
  941.     aCell:                Cell;
  942.     sndHndle:            Handle;
  943.     rType:                ResType;
  944.     theErr:                OSErr;
  945.     testID:                INTEGER;
  946.     index:                INTEGER;
  947.     numSnd:                INTEGER;
  948.     ignore:                BOOLEAN;
  949.  
  950. BEGIN
  951.     index:= 0;
  952.     SetPt(aCell, 0, 0);
  953.     IF LGetSelect(TRUE, aCell, sndDoc^.list) THEN
  954.         LSetSelect(FALSE, aCell, sndDoc^.list); {deselect any cell}
  955.     UseResFile(sndDoc^.resFile);                {count only its resources}
  956.     numSnd:= Count1Resources('snd ');        {number of sounds available}
  957.     REPEAT
  958.         index:= index + 1;
  959.         SetResLoad(FALSE);                        {don’t load any resources}
  960.         sndHndle:= Get1IndResource('snd ', index); {only get snd from file}
  961.         SetResLoad(TRUE);                            {back to normal resource operations}
  962.         GetResInfo(sndHndle, testID, rType, name);
  963.     UNTIL ((resID = testID) | (index > numSnd));
  964.     UseResFile(gAppResRef);                        {restore our resource file}
  965.     SetPt(aCell, 0, index - 1);
  966.     LSetSelect(TRUE, aCell, sndDoc^.list);
  967.     LAutoScroll(sndDoc^.list);
  968. END; {SelectSndCell}
  969.  
  970. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  971. {$S Open}
  972. FUNCTION InitSndList(docPtr: SndDocPeek): OSErr;
  973.  
  974. {This is used to create the list showing all the snd resources in the file.
  975.  If anything goes wrong while attempting to get any of the resources, then I
  976.  return false.  I don’t want the document to continue if something goes
  977.  wrong while reading a resource.  If I do get the resource, then I add its
  978.  name to the list in a new row.  I’m assured that at least one resource is
  979.  in the file before this routine is called.  Untitled resources will get one.}
  980.  
  981. VAR
  982.     index, resID,
  983.     newRow, numSnd:    INTEGER;
  984.     resHandle:            Handle;
  985.     strHandle:            StringHandle;
  986.     itsType:                ResType;
  987.     resName, untitled:Str255;
  988.     aCell:                Cell;
  989.  
  990. BEGIN
  991.     InitSndList:= noErr;
  992.     strHandle:= StringHandle(Get1Resource('STR ', rUntitled));
  993.     IF strHandle <> NIL THEN
  994.         untitled:= strHandle^^                    {save no name title}
  995.     ELSE
  996.         untitled:= '';                                {at least an empty string}
  997.     UseResFile(docPtr^.resFile);
  998.     numSnd:= Count1Resources('snd ');
  999.     newRow:= LAddRow(numSnd, 0, docPtr^.list);
  1000.     FOR index:= 1 TO numSnd DO BEGIN
  1001.         SetResLoad(FALSE);                        {don’t load any resources}
  1002.         resHandle:= Get1IndResource('snd ', index); {only get snd from file}
  1003.         SetResLoad(TRUE);                            {back to normal resource operations}
  1004.         IF resHandle <> NIL THEN BEGIN        {only if I got the snd}
  1005.             GetResInfo(resHandle, resID, itsType, resName);
  1006.             IF resName = '' THEN                    {if the snd isn’t named...}
  1007.                 resName:= untitled;                {give it a name}
  1008.             SetPt(aCell, 0, index - 1);
  1009.             LSetCell(Ptr(ORD(@resName) + 1), LENGTH(resName), aCell, docPtr^.list);
  1010.         END ELSE BEGIN {resHandle = NIL}
  1011.             InitSndList:= resNotFound;            {problem with resource file}
  1012.             index:= numSnd + 1;                    {get out of the loop}
  1013.         END;
  1014.     END;
  1015.     UseResFile(gAppResRef);                        {restore our resource file}
  1016. END;
  1017.  
  1018. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1019. {$S Open}
  1020. FUNCTION OpenByApp(vRefNum: INTEGER; dirID: LONGINT;
  1021.                         fName: StringPtr; VAR window: WindowPtr): BOOLEAN;
  1022.  
  1023. {In the case that the user has attempted to open a resource file that is
  1024.  already open, this routine will scan my open documents for it.  If I find
  1025.  that the requested file is already open by the application, then return
  1026.  true and its window pointer.  The application can then simply select that
  1027.  window.  If the resource file is open but not by this application, that’s
  1028.  a problem and I don’t use the resource file.  Many problems with using an
  1029.  open resource file.  Now if the Resource Manager would take care of this
  1030.  problem for us...}
  1031.  
  1032. VAR
  1033.     docName:                    Str255;
  1034.     testWindow:                WindowPtr;
  1035.  
  1036. BEGIN
  1037.     OpenByApp:= FALSE;
  1038.     testWindow:= FrontWindow;
  1039.     WHILE testWindow <> NIL DO BEGIN
  1040.         IF GetWRefCon(testWindow) = rSoundWindow THEN
  1041.             IF (vRefNum = SndDocPeek(testWindow)^.vRefNum)
  1042.              & (dirID = SndDocPeek(testWindow)^.dirID) THEN BEGIN
  1043.                  GetWTitle(testWindow, docName);
  1044.                 IF fName^ = docName THEN BEGIN
  1045.                     window:= testWindow;
  1046.                     OpenByApp:= TRUE;
  1047.                     EXIT(OpenByApp);
  1048.                 END;
  1049.             END;
  1050.         testWindow:= WindowPtr(WindowPeek(testWindow)^.nextWindow);
  1051.     END;
  1052. END; {OpenByApp}
  1053.  
  1054. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1055. {$S Main}
  1056. FUNCTION GetGlobalMouse: Point;
  1057.  
  1058. {Get the global coordinates of the mouse.  Get the global coordinates by
  1059.  calling GetMouse and LocalToGlobal.  This assumes the current port is a
  1060.  valid graf port.  When wouldn’t it be?}
  1061.  
  1062. VAR
  1063.     globalPt:        Point;
  1064.  
  1065. BEGIN
  1066.     GetMouse(globalPt);
  1067.     LocalToGlobal(globalPt);
  1068.     GetGlobalMouse:= globalPt;
  1069. END; {GetGlobalMouse}
  1070.  
  1071. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1072. {$S Open}
  1073. FUNCTION GetWTitleHeight(variant: INTEGER): INTEGER;
  1074.  
  1075. {Try and determine the window’s title bar height.  This isn’t easy,
  1076.  especially if the window is invisible.  We all know how the standard Apple
  1077.  System WDEF works, at least at this date we do.  I assume that method as
  1078.  shown below.  I could do what MacApp does with the Function CallWDefProc.
  1079.  If the user has installed a replacement for the System WDEF, then it’s
  1080.  their problem to deal with.  My method will work as long as Apple doesn’t
  1081.  change how the WDEF in System 6.0 calculates the title bar height.  This
  1082.  will allow my application to work on international Macs that have a larger
  1083.  system font than Chicago.  I check the window’s variant code for one that
  1084.  includes a title bar.  I will have to change this routine to adjust for
  1085.  the modal-moveable window type, which hasn’t been defined yet.
  1086.  
  1087.  In this routine, I violate my rule about not using the GetPort, SetPort,
  1088.  SetPort sequence mentioned at the start of the file. Mostly, I do this
  1089.  because it’s not all that apparent that a routine called GetWTitleHeight
  1090.  will change the port, so I make sure that it doesn’t.}
  1091.  
  1092. VAR
  1093.     info:                FontInfo;
  1094.     curGraf,
  1095.     wMgrPort:        GrafPtr;
  1096.     wTitleHeight:    INTEGER;
  1097.  
  1098. BEGIN
  1099.     IF variant IN [documentProc, noGrowDocProc,
  1100.                         zoomDocProc, zoomNoGrow, rDocProc] THEN BEGIN
  1101.         GetPort(curGraf);
  1102.         GetWMgrPort(wMgrPort);                        {I need to know the font...}
  1103.         SetPort(wMgrPort);                            {info in the System’s port}
  1104.         GetFontInfo(info);
  1105.         SetPort(curGraf);                                {restore current port}
  1106.         WITH info DO
  1107.             wTitleHeight:= ascent + descent + leading + 2;
  1108.         IF wTitleHeight < 19 THEN
  1109.             wTitleHeight:= 19;                        {the title is always at least 19}
  1110.         GetWTitleHeight:= wTitleHeight;
  1111.     END ELSE
  1112.         GetWTitleHeight:= 0;                            {other window types have no title}
  1113. END; {GetWTitleHeight}
  1114.  
  1115. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1116. {$S Main}
  1117. FUNCTION GetGlobalTopLeft(window: WindowPtr): Point;
  1118.  
  1119. {Given a window, this will return the top left point of the window’s
  1120.  port in global coordinates.  Something this doesn’t include, is the
  1121.  window’s drag region (or title bar).  This returns the top left point
  1122.  of the window’s content area only.
  1123.  
  1124.  In this routine, I violate my rule about not using the GetPort, SetPort,
  1125.  SetPort sequence mentioned at the start of the file. Mostly, I do this
  1126.  because it’s not all that apparent that a routine called GetGlobalTopLeft
  1127.  will change the port, so I make sure that it doesn’t.}
  1128.  
  1129. VAR
  1130.     theGraf:            GrafPtr;
  1131.     globalPt:        Point;
  1132.  
  1133. BEGIN
  1134.     GetPort(theGraf);
  1135.     SetPort(window);
  1136.     globalPt:= window^.portRect.topLeft;
  1137.     LocalToGlobal(globalPt);
  1138.     SetPort(theGraf);
  1139.     GetGlobalTopLeft:= globalPt;
  1140. END; {GetGlobalTopLeft}
  1141.  
  1142. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1143. {$S Main}
  1144. PROCEDURE MyParamText(text: StringHandle; cite0, cite1: StringPtr);
  1145.  
  1146. {I’m using string pointers (not necessarily Memory Manager pointers)
  1147.  to the replacement strings.  Using Str255 would copy the string to the
  1148.  stack, and then to the text handle.  This way it is only copied once.}
  1149.  
  1150. VAR
  1151.     offSet:            LONGINT;
  1152.     param0,
  1153.     param1:            PACKED ARRAY [1..2] OF CHAR;
  1154.     newLength:        LONGINT;
  1155.  
  1156. BEGIN
  1157.     param0:= '^0';
  1158.     param1:= '^1';
  1159.     IF cite0^ <> '' THEN
  1160.         offSet:= Munger(Handle(text), 1, @param0, SIZEOF(param0),
  1161.                              Ptr(ORD4(cite0) + 1), LENGTH(cite0^));
  1162.     IF cite1^ <> '' THEN
  1163.         offSet:= Munger(Handle(text), 1, @param1, SIZEOF(param1),
  1164.                              Ptr(ORD4(cite1) + 1), LENGTH(cite1^));
  1165.     newLength:= GetHandleSize(Handle(text)) - 1;
  1166.     IF newLength > 255 THEN
  1167.         newLength:= 255;
  1168.     text^^[0]:= CHAR(newLength);                        {string’s new length byte}
  1169. END;
  1170.  
  1171. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1172. {$S Open}
  1173. PROCEDURE CenterWindowRect(variant: INTEGER; VAR theRect: Rect);
  1174.  
  1175. {Given a window’s portRect, this routine will center the rectangle on the
  1176.  main device within the desktop region.  This excludes the menu bar area.
  1177.  It follows the Apple Human Interface Guidelines for where to place a
  1178.  window centered on the screen. That is, 1/3th of the desktop shows above
  1179.  the window and 2/3ths below it.  It returns a new rectangle set to the
  1180.  centered position.  The top and left of this rectangle can be used with
  1181.  MoveWindow.  This routine only considers the main device.  CenterWindowRect
  1182.  could take a GDevice as a parameter to center the VAR rect with.  This
  1183.  would also allow Alerts or dialogs that are closely associated with a
  1184.  document window to be centered relative to the monitor that contains that
  1185.  document.  This is also one of the Human Interface Guidelines.  MacApp 2.0
  1186.  has a utility CalcScreenRect that you can borrow from to include this.
  1187.  
  1188.  WARNING: This routine may move or purge memory.}
  1189.  
  1190. VAR
  1191.     rectSize:         Point;
  1192.     wTitleHeight:    INTEGER;
  1193.  
  1194. BEGIN
  1195.     wTitleHeight:= GetWTitleHeight(variant);                {get title height}
  1196.     WITH theRect DO BEGIN                                        {get size of rect}
  1197.         SetPt(rectSize, right, bottom + wTitleHeight);    {include it in size}
  1198.         SubPt(topLeft, rectSize);
  1199.     END;
  1200.     WITH screenBits.bounds DO BEGIN                            {1/3th below menubar}
  1201.         theRect.top:= ((bottom - top - GetMBarHeight - rectSize.v) DIV 3)
  1202.                           + GetMBarHeight;
  1203.         theRect.left:= ((right - left) - rectSize.h) DIV 2;    {centered horz}
  1204.     END;
  1205.     WITH theRect DO BEGIN                                        {return adjusted rect}
  1206.         SetPt(botRight, left, top);
  1207.         AddPt(rectSize, botRight);
  1208.         top:= top + wTitleHeight;                    {remove title height from rect}
  1209.     END;
  1210. END; {CenterWindowRect}
  1211.  
  1212. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1213. {$S Open}
  1214. FUNCTION GetCenteredWindow(id: INTEGER; p: Ptr; behind: WindowPtr): WindowPtr;
  1215.  
  1216. {Given a window ID, this routine will center the window’s rectangle before
  1217.  showing it on the main screen.  This follows the Apple Human Interface
  1218.  Guidelines for where to place a centered window on the screen.  If the
  1219.  window is closely associated with another window, considerations should be
  1220.  given to where that other window is located.  If this other window is on a
  1221.  screen other then the main monitor, then it would be best to center the
  1222.  window on that other monitor.
  1223.  
  1224.  VERSION 1.1: There is a problem with GetNewWindow in the old Mac Plus and
  1225.  SE ROMS.  It will call ReleaseResource on the 'WIND' resource within 
  1226.  GetNewWindow.  This make the handle invalid after the call.  Therefore,
  1227.  before calling HPurge, we get the resource once again.}
  1228.  
  1229. VAR
  1230.     newRect:            Rect;
  1231.     windTemplate:    WindowTHndl;
  1232.     window:            WindowPtr;
  1233.  
  1234. BEGIN
  1235.     window:= NIL;                                                {initialize result}
  1236.     windTemplate:= WindowTHndl(Get1Resource('WIND', id));
  1237.     IF windTemplate <> NIL THEN BEGIN
  1238.         HNoPurge(Handle(windTemplate));
  1239.         newRect:= windTemplate^^.boundsRect;
  1240.         CenterWindowRect(windTemplate^^.procID, newRect);
  1241.         windTemplate^^.boundsRect:= newRect;
  1242.         window:= GetNewWindow(id, p, behind);
  1243.         HPurge(Get1Resource('WIND', id));
  1244.     END;
  1245.     GetCenteredWindow:= window;
  1246. END;
  1247.  
  1248. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1249. {$S Open}
  1250. FUNCTION CenteredAlert(alertID: INTEGER): INTEGER;
  1251.  
  1252. {Given an Alert ID, this routine will center the alert’s rectangle before
  1253.  showing it on the main screen.  This follows the Apple Human Interface
  1254.  Guidelines for where to place a centered window on the screen.  If the
  1255.  Alert is closely associated with another window, considerations should be
  1256.  given to what the window is located.  If this other window is on a screen
  1257.  other then the main monitor, then it would be best to center the Alert on
  1258.  that other monitor.}
  1259.  
  1260. VAR
  1261.     alertHandle:    AlertTHndl;
  1262.     alertRect:        Rect;
  1263.     itemHit:            INTEGER;
  1264.  
  1265. BEGIN
  1266.     alertHandle:= AlertTHndl(Get1Resource('ALRT', alertID));
  1267.     IF alertHandle <> NIL THEN BEGIN
  1268.         HNoPurge(Handle(alertHandle));
  1269.         alertRect:= alertHandle^^.boundsRect;
  1270.         CenterWindowRect(dBoxProc, alertRect);
  1271.         alertHandle^^.boundsRect:= alertRect;
  1272.         HPurge(Handle(alertHandle));
  1273.     END;
  1274.     CenteredAlert:= Alert(alertID, NIL);
  1275. END; {CenteredAlert}
  1276.  
  1277. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1278. {$S Open}
  1279. FUNCTION GetCenteredDialog(id: INTEGER; p: Ptr; behind: WindowPtr): DialogPtr;
  1280.  
  1281. {Given a dialog ID, this routine will center the dialog’s rectangle before
  1282.  showing it on the main screen.  This follows the Apple Human Interface
  1283.  Guidelines for where to place a centered window on the screen.  If the
  1284.  dialog is closely associated with another window, considerations should be
  1285.  given to what the window is located.  If this other window is on a screen
  1286.  other then the main monitor, then it would be best to center the dialog on
  1287.  that other monitor.
  1288.   
  1289.  VERSION 1.1: There is a problem with GetNewDialog in the old Mac Plus and
  1290.  SE ROMS.  It will call ReleaseResource on the 'WIND' resource within 
  1291.  GetNewWindow.  This make the handle invalid after the call.  Therefore,
  1292.  before calling HPurge, we get the resource once again.}
  1293.  
  1294. VAR
  1295.     newRect:            Rect;
  1296.     dlogTemplate:    DialogTHndl;
  1297.     dialog:            DialogPtr;
  1298.  
  1299. BEGIN
  1300.     dialog:= NIL;                                                {initialize result}
  1301.     dlogTemplate:= DialogTHndl(Get1Resource('DLOG', id));
  1302.     IF dlogTemplate <> NIL THEN BEGIN
  1303.         newRect:= dlogTemplate^^.boundsRect;
  1304.         CenterWindowRect(dlogTemplate^^.procID, newRect);
  1305.         dlogTemplate^^.boundsRect:= newRect;
  1306.         HNoPurge(Handle(dlogTemplate));
  1307.         dialog:= GetNewDialog(id, p, behind);
  1308.         HPurge(Get1Resource('DLOG', id));
  1309.     END;
  1310.     GetCenteredDialog:= dialog;
  1311. END; {GetCenteredDialog}
  1312.  
  1313. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1314. {$S Main}
  1315. PROCEDURE DoButtonOutline(button: ControlHandle);
  1316.  
  1317. {Given any control handle, this will draw an outline around it.  This is
  1318.  used for the default button of a window.  The extra nice feature here is
  1319.  that I’ll erase the outline for buttons that are inactive.  Seems like
  1320.  there should be a Toolbox call for getting a control’s hilite state.
  1321.  Since there isn’t, I have to look into the control record myself.  This
  1322.  should be called for update and activate events.
  1323.  
  1324.  The method for determining the oval diameters for the roundrect is a
  1325.  little different than that recommended by Inside Mac.  IM I-407 suggests
  1326.  that you use a hardcoded (16,16) for the diameters. However, this only
  1327.  looks good for small roundrects. For larger ones, the outline doesn’t
  1328.  follow the inner roundrect because the CDEF for simply buttons doesn’t
  1329.  use (16,16). Instead, it uses half the height of the button as the
  1330.  diameter. By using this formula, too, our outlines look better.
  1331.  
  1332.  WARNING: This will set the current port to the control’s window.}
  1333.  
  1334. VAR
  1335.     theRect:            Rect;
  1336.     curPen:            PenState;
  1337.     buttonOval:        INTEGER;
  1338.  
  1339. BEGIN
  1340.     IF button <> NIL THEN BEGIN
  1341.         SetPort(button^^.contrlOwner);
  1342.         GetPenState(curPen);
  1343.         PenNormal;
  1344.         theRect:= button^^.contrlRect;
  1345.         InsetRect(theRect, kButtonFrameInset, kButtonFrameInset);
  1346.         buttonOval := (theRect.bottom - theRect.top) DIV 2;
  1347.         IF (button^^.contrlHilite = kCntlActivate) THEN
  1348.             PenPat(black)
  1349.         ELSE
  1350.             PenPat(gray);
  1351.         PenSize(kButtonFrameSize, kButtonFrameSize);
  1352.         FrameRoundRect(theRect, buttonOval, buttonOval);
  1353.         SetPenState(curPen);
  1354.     END;
  1355. END;
  1356.  
  1357. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1358. {$S Main}
  1359. PROCEDURE SelectButton(button: ControlHandle);
  1360.  
  1361. {Given the button control handle, this will cause the button to look as
  1362.  if it has been clicked in.  This is nice to do for the user if they type
  1363.  return or enter to select the default item.}
  1364.  
  1365. VAR
  1366.     finalTicks:        LONGINT;
  1367.  
  1368. BEGIN
  1369.     HiliteControl(button, kSelect);
  1370.     Delay(kDelayTime, finalTicks);
  1371.     HiliteControl(button, kDeselect);
  1372. END; {SelectButton}
  1373.  
  1374. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1375. {$S Main}
  1376. PROCEDURE ActivateSndCntls(sndDoc: SndDocPeek);
  1377.  
  1378. {Given a sound document, this routine goes through the control list looking
  1379.  for a control that needs to be activated, or deactivated what ever the
  1380.  case maybe.  The Play button is the default button, and it also needs its
  1381.  outline drawn.  The Stop button is always active on the front most window.
  1382.  This is true even if there is no selection made in the window’s list.  The
  1383.  Stop button is a global action, regardless of what is happening in the window.
  1384.  
  1385.  VERSION 1.1:  Stop button is only active while a sound is playing.}
  1386.  
  1387. VAR
  1388.     control:            ControlHandle;
  1389.     cntlRefCon:        LONGINT;
  1390.     activate:        BOOLEAN;
  1391.  
  1392. BEGIN
  1393.     activate:= WindowPeek(sndDoc)^.hilited & HasSelection(sndDoc);
  1394.     control:= WindowPeek(sndDoc)^.controlList;
  1395.     WHILE control <> NIL DO BEGIN
  1396.         cntlRefCon:= GetCRefCon(control);
  1397.         IF cntlRefCon IN [rPlaySndCntl, rHyperPlayCntl,
  1398.                                 rPlayScaleCntl, rMelodyCntl] THEN BEGIN
  1399.             IF activate THEN
  1400.                 HiliteControl(control, kCntlActivate)
  1401.             ELSE
  1402.                 HiliteControl(control, kCntlDeactivate);
  1403.             IF cntlRefCon = rPlaySndCntl THEN
  1404.                 DoButtonOutline(control);
  1405.         END; {IF cntlRefCon IN}
  1406.         IF cntlRefCon = rStopCntl THEN BEGIN
  1407.             IF WindowPeek(sndDoc)^.hilited & SndChanOpen THEN
  1408.                 HiliteControl(control, kCntlActivate)
  1409.             ELSE
  1410.                 HiliteControl(control, kCntlDeactivate);
  1411.         END; {cntlRefCon = rStopCntl}
  1412.         IF cntlRefCon = rRecordCntl THEN BEGIN
  1413.             IF WindowPeek(sndDoc)^.hilited THEN
  1414.                 HiliteControl(control, kCntlActivate)
  1415.             ELSE
  1416.                 HiliteControl(control, kCntlDeactivate);
  1417.         END; {cntlRefCon = rRecordCntl}
  1418.     control:= control^^.nextControl;
  1419.     END; {WHILE control <> NIL}
  1420. END;
  1421.  
  1422. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1423. {$S Main}
  1424. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  1425.  
  1426. {Check if a window belongs to a desk accessory.  This will first test for a
  1427.  NIL window.  DAs will have a negitive windowKind.}
  1428.  
  1429. BEGIN
  1430.     IF window = NIL THEN
  1431.         IsDAWindow:= FALSE
  1432.     ELSE    {DA windows have negative windowKinds}
  1433.         IsDAWindow:= WindowPeek(window)^.windowKind < 0;
  1434. END; {IsDAWindow}
  1435.  
  1436. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1437. {$S Main}
  1438. FUNCTION IsDocWindow(window: WindowPtr): BOOLEAN;
  1439.  
  1440. {Check to see if a window is a document window.  This will first test for a
  1441.  NIL window.  Document windows all have a refCon set to rSoundWindow.  This
  1442.  insures there is document type information after the window record.}
  1443.  
  1444. BEGIN
  1445.     IF window = NIL THEN
  1446.         IsDocWindow:= FALSE
  1447.     ELSE
  1448.         IsDocWindow:= GetWRefCon(window) = rSoundWindow;
  1449. END; {IsDocWindow}
  1450.  
  1451. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1452. {$S Main}
  1453. FUNCTION IsModalWindow(window: WindowPtr): BOOLEAN;
  1454.  
  1455. {This test will return TRUE for a window that needs to be treated as a
  1456.  modal window.  To include additional windows, add the window’s refCon
  1457.  value to the set of modal windows.}
  1458.  
  1459. VAR
  1460.     wRef:                LONGINT;
  1461.  
  1462. BEGIN
  1463.     IF window = NIL THEN
  1464.         IsModalWindow:= FALSE
  1465.     ELSE BEGIN
  1466.         wRef:= GetWRefCon(window);
  1467.         IsModalWindow:= wRef IN [rAboutWindow];        {set of modal windows}
  1468.     END;
  1469. END;
  1470.  
  1471. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1472. {$S Main}
  1473. PROCEDURE KillSound;
  1474.  
  1475. {This is used to free up all the sound data and channels in use.  There are
  1476.  two reasons for using this routine.  One is after a sound has completed
  1477.  the other is to terminate a sound that may be in progress.  For this
  1478.  second reason, this routine should always be used before playing a new
  1479.  sound.  When disposing of a sound channel, this sets all document’s
  1480.  sndInUse flags to FALSE.  I can call this routine at any time.  When I
  1481.  find that the memory reserve is used, I will call this to free up any
  1482.  possible sound resources which tend to be large.  Another important point
  1483.  is the human interface issue of hiding the status window.  It’s possible
  1484.  that  playing some short sounds could cause the status window to disappear
  1485.  before the user had much of a chance to see it.  To solve this, there is a
  1486.  delay that insures the status window was visible for a minimal time.
  1487.  
  1488.  VERSION 1.1:  Update the document's controls since know that the sound
  1489.  is no longer playing the buttons in the document window need to be updated.}
  1490.  
  1491. VAR
  1492.     window:            WindowPtr;
  1493.  
  1494. BEGIN
  1495.     IF SndChanOpen THEN BEGIN                                {if a channel is open...}
  1496.         window:= FrontWindow;                                {set all document’s flags}
  1497.         WHILE window <> NIL DO BEGIN
  1498.             IF IsDocWindow(window) THEN                    {if this is my document...}
  1499.                 SndDocPeek(window)^.sndInUse:= FALSE;    {then it is no longer active}
  1500.             window:= WindowPtr(WindowPeek(window)^.nextWindow);
  1501.         END;
  1502.     END;
  1503.     IF SoundCompletion THEN    BEGIN                            {why were we called?}
  1504.         DoSoundComplete;                                        {from completion}
  1505.         REPEAT                                                    {delay for status window}
  1506.         UNTIL ((TickCount - gStatusWindow^.showTime) > kShowTimeDelay);
  1507.     END ELSE
  1508.         FreeAllChans;                                            {or just because}
  1509.     HideWindow(WindowPtr(gStatusWindow));
  1510.     window:= FrontWindow;
  1511.     IF IsDocWindow(window) THEN
  1512.         ActivateSndCntls(SndDocPeek(window));
  1513. END; {KillSound}
  1514.  
  1515. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1516. {$S Main}
  1517. FUNCTION DoCloseWindow(window: WindowPtr): BOOLEAN;
  1518.  
  1519. {Close any of my windows.  At this point, if there was a document
  1520.  associated with a window, you could do any document saving processing if
  1521.  it has been changed since being opened.  DoCloseWindow would return TRUE
  1522.  if the window actually closed.  FALSE would be returned, as an example, if
  1523.  the user chose “Cancel” in the Save As… dialog.  An important detail is if
  1524.  the window to be close is one of my documents that is currently playing a
  1525.  sound.  We cannot dispose of it yet, since the sound resource owned by the
  1526.  document would be in use by the Sound Manager.  So, I test the document’s
  1527.  sndInUse flag and if it is in use I call KillSound.  The About window
  1528.  contains some resource handles.  I only mark them purgeable, but I could
  1529.  use ReleaseResource and then DisposHandle.}
  1530.  
  1531. BEGIN
  1532.     DoCloseWindow:= TRUE;
  1533.     CASE GetWRefCon(window) OF
  1534.  
  1535.         rSoundWindow: BEGIN
  1536.             IF SndDocPeek(window)^.sndInUse THEN        {contain a snd in use?}
  1537.                 KillSound;                                        {not any more}
  1538.             IF SndDocPeek(window)^.list <> NIL THEN    {dispose of document data}
  1539.                 LDispose(SndDocPeek(window)^.list);
  1540.             IF SndDocPeek(window)^.resFile <> 0 THEN
  1541.                 CloseResFile(SndDocPeek(window)^.resFile);
  1542.             KillControls(window);
  1543.             CloseWindow(WindowPtr(window));
  1544.             DisposPtr(Ptr(window));                        {dispose of our doc storage}
  1545.         END;
  1546.  
  1547.         rStatusWindow: BEGIN
  1548.             KillControls(WindowPtr(gStatusWindow));
  1549.             DisposHandle(Handle(gStatusWindow^.message));
  1550.             CloseWindow(WindowPtr(gStatusWindow));
  1551.             DisposPtr(Ptr(gStatusWindow));
  1552.         END;
  1553.  
  1554.         rAboutWindow: BEGIN
  1555.             IF AboutWPeek(window)^.comment <> NIL THEN        {never dispose...}
  1556.                 HPurge(AboutWPeek(window)^.comment);            {a Resource handle}
  1557.             IF AboutWPeek(window)^.appPict <> NIL THEN
  1558.                 HPurge(AboutWPeek(window)^.appPict);
  1559.             IF AboutWPeek(window)^.appIcon <> NIL THEN
  1560.                 IF AboutWPeek(window)^.iconIsColor THEN
  1561.                     DisposCIcon(CIconHandle(AboutWPeek(window)^.appIcon))
  1562.                 ELSE
  1563.                     HPurge(AboutWPeek(window)^.appIcon);         {disposCIcon}
  1564.             KillControls(window);
  1565.             CloseWindow(WindowPtr(window));
  1566.             DisposPtr(Ptr(window));
  1567.         END;
  1568.  
  1569.         OTHERWISE
  1570.             IF IsDAWindow(window) THEN                        {we can close DAs too}
  1571.                 CloseDeskAcc(WindowPeek(window)^.windowKind);
  1572.  
  1573.     END; {CASE GetWRefCon(window)}
  1574. END; {DoCloseWindow}
  1575.  
  1576. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1577. {$S Main}
  1578. PROCEDURE AlertUser(error: INTEGER; messageID: INTEGER);
  1579.  
  1580. {Display an alert to inform the user of an error.  MessageID acts as an
  1581.  index into a STR# resource of error messages.  This will attempt to
  1582.  replace the error number with a string if the sound is a Sound Manager
  1583.  error.
  1584.  
  1585.  BUG NOTE: GetIndString will return a bogus string if the index is not
  1586.  positive.}
  1587.  
  1588. VAR
  1589.     msg1, msg2:        Str255;
  1590.     theItem:            INTEGER;
  1591.  
  1592. BEGIN
  1593.     UseResFile(gAppResRef);                                {restore our resource file}
  1594.     IF messageID > 0 THEN
  1595.         GetIndString(msg1, sErrStrings, messageID)
  1596.     ELSE
  1597.         msg1:= '';                                            {in case there is no message}
  1598.     IF (error <= noHardware) & (error >= siUnknownQuality) THEN
  1599.         GetIndString(msg2, sSMErrStrings, ABS(error) + noHardware + 1)
  1600.     ELSE
  1601.         NumToString(error, msg2);
  1602.     ParamText(msg1, msg2, '', '');
  1603.     theItem:= CenteredAlert(rUserAlert);
  1604. END; {AlertUser}
  1605.  
  1606. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1607. {$S Main}
  1608. PROCEDURE EmergencyExit(message: INTEGER);
  1609.  
  1610. {Display an alert that tells the user an error occurred, then exit the
  1611.  program.  This routine is used as an ultimate bail-out for serious errors
  1612.  that prohibit the continuation of the application.  Errors that do not
  1613.  require the termination of the application are handled with AlertUser.
  1614.  Error checking and reporting has a place even in the simplest application.
  1615.  
  1616.  BUG NOTE: GetIndString will return a bogus string if the index is not
  1617.  positive.}
  1618.  
  1619. VAR
  1620.     msg1:                Str255;
  1621.     theItem:            INTEGER;
  1622.  
  1623. BEGIN
  1624.     SetCursor(arrow);
  1625.     IF message > 0 THEN
  1626.         GetIndString(msg1, sErrStrings, message)
  1627.     ELSE
  1628.         msg1:= '';                                            {in case there is no message}
  1629.     ParamText(msg1, '', '', '');
  1630.     theItem:= CenteredAlert(rExitAlert);
  1631.     ExitToShell;                                            {we’re out of here}
  1632. END; {EmergencyExit}
  1633.  
  1634. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1635. {$S Main}
  1636. PROCEDURE Terminate;
  1637.  
  1638. {Clean up the application and exit.  I close all of the windows so that
  1639.  they can update their documents, if any.  Dispose of the Sound Unit and
  1640.  close the status window if the user really wants to quit.}
  1641.  
  1642. VAR
  1643.     aWindow:        WindowPtr;
  1644.     closed:        BOOLEAN;
  1645.  
  1646. BEGIN
  1647.     closed:= TRUE;
  1648.     KillSound;                                            {stop any sound in progress}
  1649.     REPEAT
  1650.         aWindow:= FrontWindow;                        {get the current front window}
  1651.         IF aWindow <> NIL THEN
  1652.             closed:= DoCloseWindow(aWindow);        {close this window}
  1653.     UNTIL (NOT closed) | (aWindow = NIL);        {do all windows}
  1654.     IF closed THEN BEGIN
  1655.         FreeSoundUnit;                                    {get rid of all sound equipment}
  1656.         ExitToShell;                                    {exit if no cancellation}
  1657.     END;
  1658. END; {Terminate}
  1659.  
  1660. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1661. {$S Main}
  1662. PROCEDURE DrawStatusWindow;
  1663.  
  1664. {Draw the status message and update the button.  I setup a rectangle that
  1665.  is the text area.  This is the entire window area, inset a small amount.
  1666.  I also subtract from the bottom of the rectangle the area used by the button.
  1667.  Doing things this way allowed me to change the size of the window and
  1668.  not change any of this code.  The rectangle used by text will fill the
  1669.  window regardless of the new size I give it in the WIND resource.}
  1670.  
  1671. VAR
  1672.     theRect:         Rect;
  1673.  
  1674. BEGIN
  1675.     PenNormal;
  1676.     WITH WindowPtr(gStatusWindow)^.portRect DO
  1677.         SetRect(theRect, left, top, right, bottom - kDafaultButSizeH);
  1678.     InsetRect(theRect, kMsgInset, kMsgInset);
  1679.     HLock(Handle(gStatusWindow^.message));
  1680.     TextBox(Ptr(ORD(gStatusWindow^.message^) + 1),
  1681.                 LENGTH(gStatusWindow^.message^^), theRect, teJustCenter);
  1682.     HUnlock(Handle(gStatusWindow^.message));
  1683.     UpdtControl(WindowPtr(gStatusWindow), WindowPtr(gStatusWindow)^.visRgn);
  1684.     DoButtonOutline(WindowPeek(gStatusWindow)^.controlList);
  1685. END; {DrawStatusWindow}
  1686.  
  1687. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1688. {$S Main}
  1689. PROCEDURE ShowStatusWindow(messageID: INTEGER);
  1690.  
  1691. {Whenever I start a sound, I show this status window.  It will contain a
  1692.  message showing what is currently happening.  A very good rule is not to
  1693.  perform drawing outside of the update event.  I bend that rule here.  I
  1694.  could simply select this window and show it.  This would allow my normal
  1695.  drawing and activating routines to be called.  The problem with that was,
  1696.  I found that many times the status window appeared and then disappeared
  1697.  before these update routines had a chance to draw the window.  This left
  1698.  the user with a blank window that immediately went away.  So, I do the
  1699.  activation and drawing right after showing it.
  1700.  
  1701.  BUG NOTE: GetIndString will return a bogus string if the index is not
  1702.  positive.}
  1703.  
  1704. VAR
  1705.     msg:                Str255;
  1706.  
  1707. BEGIN
  1708.     IF FailLowMemory(0) THEN BEGIN                            {running low on memory?}
  1709.         KillSound;
  1710.         AlertUser(memFullErr, sLowMemory);
  1711.     END ELSE BEGIN
  1712.         IF messageID > 0 THEN
  1713.             GetIndString(msg, sMsgStrings, messageID)
  1714.         ELSE
  1715.             msg:= '';                                                {case there’s no message}
  1716.         SetString(gStatusWindow^.message, msg);
  1717.         ShowWindow(WindowPtr(gStatusWindow));                {show the window}
  1718.         SelectWindow(WindowPtr(gStatusWindow));            {bring it to the front}
  1719.         SetPort(GrafPtr(gStatusWindow));
  1720.         EraseRect(WindowPtr(gStatusWindow)^.portRect);    {erase the old message}
  1721.         HiliteControl(WindowPeek(gStatusWindow)^.controlList, kCntlActivate);
  1722.         DrawStatusWindow;                                            {draw the new message}
  1723.         ValidRect(WindowPtr(gStatusWindow)^.portRect);    {avoid a needless update}
  1724.         gStatusWindow^.showTime:= TickCount;                {it’s show time folks}
  1725.     END;
  1726. END; {ShowStatusWindow}
  1727.  
  1728. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1729. {$S Initialization}
  1730. PROCEDURE InitStatusWindow;
  1731.  
  1732. {This initializes the status window, and keeps it hidden until the user
  1733.  decides to play a sound.  I also center it for the first time, but the
  1734.  user is free to drag it to a new location afterwards.  The status window
  1735.  also has a message associated to it, so I allocate a string handle for this.}
  1736.  
  1737. VAR
  1738.     window:            WindowPtr;
  1739.     stopButton:        ControlHandle;
  1740.  
  1741. BEGIN
  1742.     gStatusWindow:= StatWindowPeek(NewPtrClear(SIZEOF(StatusWindow)));
  1743.     IF gStatusWindow = NIL THEN
  1744.         EmergencyExit(sInitStatusErr);
  1745.     window:= GetCenteredWindow(rStatusWindow, Ptr(gStatusWindow), Pointer(-1));
  1746.     IF window = NIL THEN
  1747.         EmergencyExit(sInitStatusErr);
  1748.     SetWRefCon(window, rStatusWindow);
  1749.     stopButton:= GetNewControl(rCancelCntl, window);
  1750.     IF stopButton = NIL THEN
  1751.         EmergencyExit(sInitStatusErr);
  1752.     gStatusWindow^.message:= NewString('');        {a new empty string handle}
  1753.     IF gStatusWindow^.message = NIL THEN
  1754.         EmergencyExit(sInitStatusErr);
  1755.     HNoPurge(Handle(gStatusWindow^.message));
  1756. END; {InitStatusWindow}
  1757.  
  1758. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1759. {$S Main}
  1760. PROCEDURE DoErrorSound(soundNo: INTEGER);
  1761.  
  1762. {I just flash the menubar for a moment instead of playing any sounds.  It’s
  1763.  the same effect as setting the sound volume to zero but that would prevent
  1764.  me playing my sounds.  Also, it helps to prevent the problem of _SysBeep
  1765.  being called by the Dialog Manager while I’m playing a sound.  If my
  1766.  application is playing a sound and, for example, the user clicks outside
  1767.  of the Standard File dialog ModalDialog calls _SysBeep.  This can cause
  1768.  the Mac to crash or trash my channel.
  1769.  
  1770.  BUG NOTE: If the current Sound Manager were playing a sound and a
  1771.  _SysBeep were to occur, bad things could happen on a Mac Plus/SE.  Either
  1772.  the application’s channel would be trashed or the Mac could crash.
  1773.  
  1774.  VERSION 1.1: The new Sound Manager will handle the problem presented in the 
  1775.  older Sound Manager regarding SysBeep.  If I'm running under the new Sound 
  1776.  Manager then I'll call SysBeep anyway.  The new Sound Manager will properly 
  1777.  handle the situation of an open sound channel when SysBeep is called.}
  1778.  
  1779. VAR
  1780.     finalTicks:        LongInt;
  1781.  
  1782. BEGIN
  1783.     IF HasNewSndMgr THEN
  1784.         SysBeep(30)                                            {does the right thing now}
  1785.     ELSE BEGIN
  1786.         IF soundNo > 0 THEN BEGIN                        {only after the first time}
  1787.             FlashMenuBar(0);
  1788.             Delay(kDelayTime, finalTicks);
  1789.             FlashMenuBar(0);
  1790.         END;
  1791.     END;
  1792. END;
  1793.  
  1794. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1795. {$S Initialization}
  1796. PROCEDURE CheckSndVol;
  1797.  
  1798. {This tests if the volume has been set very low.  It’s a judgement call as
  1799.  to what “too low” means.  The user sets the volume, so how could it be too
  1800.  low? A setting of 0 could be considered too low, but in any case do not
  1801.  adjust it.  I find the volume goes below 4 on a standard Mac, then there
  1802.  is a perceivable difference.  I also wanted to show this routine as a
  1803.  demonstration in how to handle such a situation.  Do not change it
  1804.  directly! Ask the user to do it.  Consider the user that has their Mac
  1805.  connected to a stack of Marshalls (which go to 11) and has purposely set
  1806.  their Mac’s volume where they wanted it.  This may be 3 and if you crack
  1807.  it up to 8, it could be a scene out of Back to the Future.
  1808.  
  1809.  User Interface rule, let the user remain in control!}
  1810.  
  1811. VAR
  1812.     curVol,
  1813.     item:            INTEGER;
  1814.     numStr:        Str255;
  1815.  
  1816. BEGIN
  1817.     GetSoundVol(curVol);
  1818.     IF (curVol < kMinVolumeDesired) THEN BEGIN
  1819.         NumToString(curVol, numStr);
  1820.         ParamText(numStr, '', '', '');                    {show the current volume}
  1821.         item:= CenteredAlert(rSoundVolAlert);
  1822.     END;
  1823. END;
  1824.  
  1825. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1826. {$S Open}
  1827. PROCEDURE AddSndDocControls(window: WindowPtr);
  1828.  
  1829. {Simply add all the buttons I want to use in the document window.  I get
  1830.  the control templates, and add the control to the window.  I don’t check
  1831.  for getting errors for two reasons.  I put these controls there.  If the
  1832.  user removes them, it’s their problem.  If the application cannot get the
  1833.  memory required for these, then the application is already out of memory
  1834.  and checking here probably wouldn’t help much.  I do check before creating
  1835.  the document that there was enough available memory.  I save the resource
  1836.  ID into the control’s refCon so later I can tell which control was hit by
  1837.  the user.
  1838.  
  1839.  VERSION 1.1: Add the record button to the window.}
  1840.  
  1841. VAR
  1842.     control:                    ControlHandle;
  1843.  
  1844. BEGIN
  1845.     control:= GetNewControl(rPlaySndCntl, window);
  1846.     IF control <> NIL THEN
  1847.         SetCRefCon(control, rPlaySndCntl);
  1848.     control:= GetNewControl(rHyperPlayCntl, window);
  1849.     IF control <> NIL THEN
  1850.         SetCRefCon(control, rHyperPlayCntl);
  1851.     control:= GetNewControl(rPlayScaleCntl, window);
  1852.     IF control <> NIL THEN
  1853.         SetCRefCon(control, rPlayScaleCntl);
  1854.     control:= GetNewControl(rMelodyCntl, window);
  1855.     IF control <> NIL THEN
  1856.         SetCRefCon(control, rMelodyCntl);
  1857.     control:= GetNewControl(rStopCntl, window);
  1858.     IF control <> NIL THEN
  1859.         SetCRefCon(control, rStopCntl);
  1860.     control:= GetNewControl(rRecordCntl, window);
  1861.     IF control <> NIL THEN
  1862.         SetCRefCon(control, rRecordCntl);
  1863. END;
  1864.  
  1865. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1866. {$S Open}
  1867. FUNCTION NewStackedWindow(windID: INTEGER; windStorage: Ptr): WindowPtr;
  1868.  
  1869. {There are a few approaches I thought of and tried, none of which satisfied
  1870.  me.  ResEdit uses the simplest method, an offset from the front window.  I
  1871.  don’t like this because it may cover up existing windows.  So my approach is
  1872.  to go through the window list looking for an empty spot.  If the empty
  1873.  spot causes the window to go off the screen, then I start a new stack off
  1874.  to the right.  This will cause a new series of window to be stacked.  If the
  1875.  new stack would cause the window to go off screen, then it’s time to give up.
  1876.  All new windows will then be moved to the starting point and there is no
  1877.  further stacking.  If I look at this routine too much, I get real tired.
  1878.  If I try to change it at all, I get woozy trying to make it work again.}
  1879.  
  1880. CONST
  1881.     kStartPt =            2;            {offset from the topLeft of the screen}
  1882.     kStaggerH =            16;        {staggering amounts for new windows}
  1883.     kStaggerV =            3;            {not including the window’s title height}
  1884.  
  1885. VAR
  1886.     windSize, newPt,
  1887.     oldPt, delta:        Point;
  1888.     newWindow,
  1889.     oldWindow:            WindowPtr;
  1890.     wTitleHeight,
  1891.     numStacks:            INTEGER;
  1892.     taken:                BOOLEAN;
  1893.  
  1894.     FUNCTION PositionAvailable: BOOLEAN;
  1895.     BEGIN
  1896.         taken:= FALSE;
  1897.         oldWindow:= FrontWindow;
  1898.         WHILE (oldWindow <> NIL) & NOT taken DO BEGIN
  1899.             IF IsDocWindow(oldWindow) & WindowPeek(oldWindow)^.visible THEN BEGIN
  1900.                 oldPt:= GetGlobalTopLeft(oldWindow);
  1901.                 delta.v:= ABS(newPt.v - oldPt.v);
  1902.                 delta.h:= ABS(newPt.h - oldPt.h);
  1903.                 taken:= (delta.h + delta.v)
  1904.                           <= ((kStaggerH + kStaggerV + wTitleHeight) DIV 2);
  1905.             END;
  1906.             oldWindow:= WindowPtr(WindowPeek(oldWindow)^.nextWindow);
  1907.         END;
  1908.         PositionAvailable:= NOT taken;
  1909.     END;
  1910.  
  1911.     FUNCTION OutOfBounds: BOOLEAN;
  1912.     BEGIN
  1913.         OutOfBounds:= ((newPt.v + windSize.v) > screenBits.bounds.bottom)
  1914.                          | ((newPt.h + windSize.h) > screenBits.bounds.right);
  1915.     END;
  1916.  
  1917. BEGIN {set the initail starting point for a window, less the staggering amount}
  1918.     newWindow:= GetNewWindow(windID, windStorage, WindowPtr(-1));
  1919.     windSize:= newWindow^.portRect.botRight;
  1920.     SubPt(newWindow^.portRect.topLeft, windSize);
  1921.     wTitleHeight:= GetWTitleHeight(GetWVariant(newWindow));
  1922.     SetPt(newPt, kStartPt - kStaggerH, kStartPt - kStaggerV + GetMBarHeight);
  1923.  
  1924.     REPEAT {add the staggering amount then test if the window goes off the screen}
  1925.         taken:= TRUE;
  1926.         SetPt(newPt, newPt.h + kStaggerH, newPt.v + kStaggerV + wTitleHeight);
  1927.         IF OutOfBounds THEN BEGIN
  1928.              numStacks:= numStacks + 1;
  1929.             SetPt(newPt, kStartPt + (numStacks * kStaggerH),
  1930.                               kStartPt + wTitleHeight + GetMBarHeight);
  1931.             IF OutOfBounds THEN BEGIN
  1932.                 SetPt(newPt, kStartPt, kStartPt + wTitleHeight + GetMBarHeight);
  1933.                 taken:= FALSE;
  1934.             END;
  1935.         END;
  1936.     UNTIL NOT taken | PositionAvailable;
  1937.  
  1938.     MoveWindow(newWindow, newPt.h, newPt.v, TRUE);
  1939.     NewStackedWindow:= newWindow;
  1940. END; {NewStackedWindow}
  1941.  
  1942. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  1943. {$S Open}
  1944. FUNCTION CreateSoundDoc(resRef: INTEGER; fNamePtr: StringPtr;
  1945.                             vRefNum: INTEGER; dirID: LONGINT): OSErr;
  1946.  
  1947. {Create a sound document and initialize all the data associated with
  1948.  it.  If I encounter an error, then dispose of any memory allocated in the
  1949.  attempt.  Allocate all necessary memory required for a sound document.  I
  1950.  like to use NewPtrClear because is will initialize all the memory.  I
  1951.  depend on real values or zero in my document fields.  Then its time to
  1952.  build a sound document which contains all the controls and the list of
  1953.  sounds.  I get the position for the list kept in a rectangle resource.
  1954.  This  helps me to adjust the size of the list without changing code.  I
  1955.  will make  an additional adjustment to the list’s height to insure better
  1956.  scrolling.  This avoids the ugly white space of an improperly sized
  1957.  rectangle.  If I  cannot create the list, I’ll close the window and return
  1958.  a NIL.  If I find  after creating a new document that I’m low on memory,
  1959.  I’ll close it and  return an error.
  1960.  
  1961.  SPECIAL NOTE: The Human Interface Group suggested that the buttons and the
  1962.  list should in the System font.  I designed these windows using the
  1963.  application font in 10 point.  If you change the call to TextFont, you'll
  1964.  find that the buttons and the list will work properly in your font choice.
  1965.  
  1966.  VERSION 1.1:  Size the window smaller to hide the record button from the
  1967.  user if Sound Input is not available.  Added memory check to the beginning
  1968.  of this routine before creating the document.  This was done because there
  1969.  are two routines that call this one, OpenSoundDoc and NewSoundDoc which
  1970.  both performed this check.  Having here in one place reduces the chance of
  1971.  future bugs (doing the same thing in two places) and reduces the size of
  1972.  the code.}
  1973.  
  1974. VAR
  1975.     newDocPtr:                SndDocPeek;
  1976.     window:                    WindowPtr;
  1977.     list:                        ListHandle;
  1978.     rHandle:                    RectHandle;
  1979.     lView, lBounds:        Rect;
  1980.     aCell:                    Cell;
  1981.     cSize, newSize:        Point;
  1982.     maxListHeight:            INTEGER;
  1983.     theErr:                    OSErr;
  1984.     ignore:                    BOOLEAN;
  1985.  
  1986. BEGIN
  1987.     IF FailLowMemory(kMemForSndDoc) THEN BEGIN
  1988.         CloseResFile(resRef);                            {close it before leaving}
  1989.         CreateSoundDoc:= memFullErr;
  1990.         EXIT(CreateSoundDoc);
  1991.     END;
  1992.     newDocPtr:= SndDocPeek(NewPtrClear(SIZEOF(SndDocument)));
  1993.     theErr:= MemError;
  1994.     IF newDocPtr <> NIL THEN BEGIN
  1995.         window:= NewStackedWindow(rSoundWindow, Ptr(newDocPtr));
  1996.         SetPort(window);
  1997.         IF HasSoundInput THEN
  1998.             SizeWindow(window, kSoundWindowSizeW, kSoundWindowSizeH, FALSE);
  1999.         TextFont(0);                                        {set window to System font, blech}
  2000.         AddSndDocControls(window);                        {add my buttons}
  2001.         SetWRefCon(WindowPtr(newDocPtr), rSoundWindow); {mark as an app window}
  2002.         SetWTitle(WindowPtr(newDocPtr), fNamePtr^);
  2003.         newDocPtr^.resFile:= resRef;                    {save its resource file ref}
  2004.         newDocPtr^.vRefNum:= vRefNum;                    {save its volume reference}
  2005.         newDocPtr^.dirID:= dirID;                        {save its directory ID}
  2006.         newDocPtr^.sndInUse:= FALSE;                    {not yet it doesn’t}
  2007.         rHandle:= RectHandle(Get1Resource('RECT', rListRectID));
  2008.         IF rHandle <> NIL THEN                            {get the stored list size}
  2009.             lView:= rHandle^^;
  2010.         SetRect(lBounds, 0, 0, 1, 0);                    {one dimentional list}
  2011.         SetPt(cSize, 0, 0);                                {List Mgr will find cell size}
  2012.         list:= LNew(lView, lBounds, cSize, 0, window, FALSE, FALSE, FALSE, TRUE);
  2013.         WITH window^.portRect DO
  2014.             maxListHeight:= bottom - top - (2 * kSndStdSpacing);
  2015.         IF maxListHeight < (lView.bottom - lView.top) THEN
  2016.             maxListHeight:= (lView.bottom - lView.top);
  2017.         IF list <> NIL THEN BEGIN
  2018.             newSize:= list^^.cellSize;                    {get the size of one cell}
  2019.             WHILE (newSize.v + list^^.cellSize.v) < maxListHeight DO
  2020.                 newSize.v:= newSize.v + list^^.cellSize.v;
  2021.             LSize(newSize.h, newSize.v, list);        {adjust for best scrolling}
  2022.             list^^.selFlags:= lOnlyOne;                {single selections only}
  2023.             newDocPtr^.list:= list;                        {save the list handle}
  2024.             theErr:= InitSndList(newDocPtr);            {initialize the list data}
  2025.             IF theErr = noErr THEN BEGIN
  2026.                 SetPt(aCell, 0, 0);                        {by default, I will...}
  2027.                 LSetSelect(TRUE, aCell, newDocPtr^.list); {select first item}
  2028.                 LDoDraw(TRUE, newDocPtr^.list);
  2029.                 ShowWindow(WindowPtr(newDocPtr));    {get the show on the road}
  2030.                 IF FailLowMemory(0) THEN                {if I’m low on memory...}
  2031.                     theErr:= memFullErr;
  2032.             END;
  2033.         END ELSE
  2034.             theErr:= nilHandleErr;                        {list handle was NIL}
  2035.         IF theErr <> noErr THEN BEGIN                    {could not create the list}
  2036.             ignore:= DoCloseWindow(window);            {if not, close the window}
  2037.             newDocPtr:= NIL;                                {return NIL pointer too}
  2038.         END;
  2039.     END;
  2040.     CreateSoundDoc:= theErr;                            {return the error, if any}
  2041. END; {CreateSoundDoc}
  2042.  
  2043. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2044. {$S Open}
  2045. PROCEDURE OpenSoundDoc(fNamePtr: StringPtr; wdVRefNum: INTEGER);
  2046.  
  2047. {Believe it or not, but this turned out to be one of the more difficult
  2048.  routines to write.  This was the best approach I could thing of to avoid
  2049.  serious problems.  I don’t center the Standard File dialog because it
  2050.  wouldn’t be under the File menu where the user probably has the mouse.  I
  2051.  use OpenRFPerm because it allows for permissions and doesn’t depend on the
  2052.  current directory.  First problem with opening a resource file was to
  2053.  check if the file already being open.  Read Tech Notes #116 and #185.
  2054.  GetFInfo seems to do the trick.  At least it does report all files that
  2055.  are open on this machine.  It may be incorrect for files on AppleShare
  2056.  opened by other machines.  What I’m worried about is when opening a
  2057.  resource file for the second time on the same machine may return the
  2058.  previous opener’s resource map.  This is very dangerous, and if the second
  2059.  opener calls CloseResFile there will be a crash.  I want to be friendly
  2060.  and if the user tries to open the file the second time and I’ve already
  2061.  got it on the screen, then I’ll bring that window forward.  To test for
  2062.  this, I compare the file’s name, DirID and vRefNum.  The vRefNum is
  2063.  dynamic and needs to be converted into a volume name if I were to save
  2064.  this information for future use.
  2065.  
  2066.  There are a couple pitfalls, even with this method.  The user can open the
  2067.  file, then move it to another directory.  This same thing confuses all
  2068.  other applications I’ve tested.  Opening a resource file will allocate a
  2069.  resource map handle into my heap, which may be large depending on the
  2070.  number of resources in that file.  Additionally this loads all resources
  2071.  marked “preload.”  So I set ResLoad to FALSE to prevent the preloading.  I
  2072.  test if the amount of memory I believe my document will require is
  2073.  available after opening the resource file.  If true, I test if there are
  2074.  any sound resources in that file and if not alert the user.  After all
  2075.  this, create the new document.  If after creating the new document I find
  2076.  that memory is too low, will close it and return an error.  If it does
  2077.  fail, then close the file before anything else or there may not be enough
  2078.  memory to show the alert.  All of these tests created a number of
  2079.  IF-THEN-ELSE blocks and became unyielding.  C programmers get a break, so
  2080.  gimme me one too.  I use the MPW Pascal EXIT.
  2081.  
  2082.  BUG NOTE: Don’t open a resource file that is already open.  OpenResFile
  2083.  may return an existing resource map when it gets opWrErr from the file
  2084.  system.  If this happens, the resource file will not be unique and this
  2085.  is very bad.  Another problem is if I get a read-only path and someone
  2086.  else opens it for read/write.  This is also very bad.  Read Tech Notes
  2087.  #116 and #185 hint at this problem, but I think a more comprehensive one
  2088.  is in order.
  2089.  
  2090.  BUG NOTE: GetWDInfo fails with nsvErr if the working directory returned
  2091.  from Standard File is the root of an A/UX volume.  I could work around
  2092.  this,  but it would be dependant on the current version of A/UX.  Read
  2093.  Tech Note #229.  I believe this is also true for TOPS.
  2094.  
  2095.  VERSION 1.1:  I'll open files that do not have snd resources in them.  
  2096.  This allows users to open existing files and then record or paste a sound 
  2097.  into it.  I changed OpenRFPerm to HOpenResFile to avoid working 
  2098.  directories and to be consistent with the rest of the sources.  I 
  2099.  separated the standard file code from OpenSndDoc to support opening 
  2100.  documents being open from the Finder.  This allows me to share the same 
  2101.  routine to open files either from double clicking them in the Finder, or 
  2102.  by the Standard File dialog.  Removed the checking for low memory conditions
  2103.  since CreateSoundDoc is now doing this.}
  2104.  
  2105. VAR
  2106.     fPBRec:            ParamBlockRec;
  2107.     window:            WindowPtr;
  2108.     dirID, procID:    LONGINT;
  2109.     resFileRef,
  2110.     vRefNum,
  2111.     numSnds:            INTEGER;
  2112.     theErr:            OSErr;
  2113.  
  2114. BEGIN
  2115.     WITH fPBRec DO BEGIN                                {prepare a paramBlock}
  2116.         ioCompletion:= NIL;
  2117.         ioNamePtr:= fNamePtr;
  2118.         ioVRefNum:= wdVRefNum;
  2119.         ioFVersNum:= 0;
  2120.         ioFDirIndex:= 0;
  2121.     END;                                                    {get file location}
  2122.     theErr:= GetWDInfo(wdVRefNum, vRefNum, dirID, procID);
  2123.     IF theErr <> noErr THEN BEGIN
  2124.         AlertUser(theErr, sStandardErr);            {this fails at the root on A/UX}
  2125.         Exit(OpenSoundDoc);
  2126.     END;
  2127.     theErr:= PBGetFInfo(@fPBRec, NOT kFSAsynch); {fPBRec on stack, synch only}
  2128.     IF theErr = noErr THEN BEGIN
  2129.         IF BTst(fPBRec.ioFlAttrib, kResForkOpenBit) THEN BEGIN
  2130.             IF OpenByApp(vRefNum, dirID, fNamePtr, window) THEN
  2131.                 SelectWindow(window)                    {I opened this one, select it}
  2132.             ELSE
  2133.                 AlertUser(noErr, sCurInUseErr);    {in use by someone else}
  2134.             Exit(OpenSoundDoc);
  2135.         END;
  2136.     END ELSE BEGIN
  2137.         AlertUser(theErr, sStandardErr);            {PBGetFInfo failed}
  2138.         Exit(OpenSoundDoc);
  2139.     END;
  2140.     SetResLoad(FALSE);                                {don’t load any resources}
  2141.     resFileRef:= HOpenResFile(vRefNum, dirID, fNamePtr^, fsCurPerm);
  2142.     theErr:= ResError;                                {save error, if any}
  2143.     SetResLoad(TRUE);                                    {restore ResLoad state}
  2144.     UseResFile(gAppResRef);                            {changes ResErr}
  2145.     IF resFileRef <> -1 THEN                        {error from OpenRFPerm?}
  2146.         theErr:= CreateSoundDoc(resFileRef, fNamePtr, vRefNum, dirID);
  2147.     IF theErr <> noErr THEN
  2148.         AlertUser(theErr, sNewDocErr);             {couldn’t create new doc}
  2149. END; {OpenSoundDoc}
  2150.  
  2151. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2152. {$S Open}
  2153. PROCEDURE NewSoundDoc;
  2154.  
  2155. {VERSION 1.1:  Create a new file for the user.  I prefer to use the new 
  2156.  HCreateResFile to avoid working directories, and to be consistent with 
  2157.  the rest of the sources.  Also, I need the real vRefNum and dirID to 
  2158.  store in the sndDoc record.  After creating the file, I set its Finder 
  2159.  information to the proper type and creator.  Finally, I get to open the 
  2160.  new file.  After this point everything is exactly like opening an 
  2161.  existing file and creating a new sound document.}
  2162.  
  2163. VAR
  2164.     msg:                Str255;
  2165.     reply:            SFReply;
  2166.     fndrInfo:        FInfo;
  2167.     strHandle:        StringHandle;
  2168.     dirID:            LONGINT;
  2169.     procID:            LONGINT;
  2170.     vRefNum:            INTEGER;
  2171.     resFileRef:        INTEGER;
  2172.     theErr:            OSErr;
  2173.  
  2174. BEGIN
  2175.     theErr:= noErr;
  2176.     strHandle:= StringHandle(Get1Resource('STR ', rPutFileMsg));
  2177.     IF strHandle <> NIL THEN
  2178.         msg:= strHandle^^                                        {save no name title}
  2179.     ELSE
  2180.         msg:= '';                                                {at least an empty string}
  2181.     SFPutFile(Point(kSFTopLeft), msg, '', NIL, reply);
  2182.  
  2183.     IF reply.good THEN BEGIN
  2184.         theErr:= GetWDInfo(reply.vRefNum, vRefNum, dirID, procID);
  2185.         HCreateResFile(vRefNum, dirID, reply.fName);
  2186.         theErr:= ResError;
  2187.         IF theErr = noErr THEN BEGIN
  2188.             theErr:= HGetFInfo(vRefNum, dirID, reply.fName, fndrInfo);
  2189.             IF theErr = noErr THEN BEGIN
  2190.                 fndrInfo.fdType:= rSndAppDocType;
  2191.                 fndrInfo.fdCreator:= rAppSignature;
  2192.                 theErr:= HSetFInfo(vRefNum, dirID, reply.fName, fndrInfo);
  2193.                 resFileRef := HOpenResFile(vRefNum, dirID, reply.fName, fsCurPerm);
  2194.                 theErr:= ResError;                            {save error, if any}
  2195.                 UseResFile(gAppResRef);                        {changes ResErr}
  2196.                 IF resFileRef <> -1 THEN                    {error from HOpenResFile}
  2197.                     theErr:= CreateSoundDoc(resFileRef, @reply.fName, vRefNum, dirID);
  2198.             END;
  2199.         END;
  2200.     END;
  2201.     IF theErr <> noErr THEN
  2202.         AlertUser(theErr, sNewDocErr);                     {return the error}
  2203. END;
  2204.  
  2205. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2206. {$S Open}
  2207. FUNCTION SFFilter(p: ParmBlkPtr): BOOLEAN;
  2208.  
  2209. {This is much more than what a typical file filter might do but I wanted
  2210.  the user to easily find files that contained snd resources.  So, the
  2211.  global flag gSndFilesOnly is used to determine when to filter for such
  2212.  files.  Otherwise, I show all files and allow the application to report to
  2213.  the user the file they’ve just tried to open doesn’t have any sounds to
  2214.  play with.  Opening resource forks can be tricky if it’s already open.  It
  2215.  would be very bad to use a resource fork that is already open by another
  2216.  application.  The problem being that the Resource Manager doesn’t deal
  2217.  with multiple users.  Read Tech notes #116 and #185.  There’s also another
  2218.  problem.  If a resource fork is opened by two applications and one closes
  2219.  the file then the entire resource fork may closed out from underneath the
  2220.  other application.  I do, however, want to show the user files that
  2221.  contain sound resources even if they are currently open.  I use
  2222.  HOpenResFile with read only permission, which will give me a unique
  2223.  resource reference.  I look for a 'snd ' resource and then immediately
  2224.  close the file.  Do not use a resource file opened with read only
  2225.  permission.  Another reason to use HOpenResFile is to avoid a necessary
  2226.  working directory.  I do not have one while in the file filter, but can
  2227.  use the DirID.  Performing this search on each file is time consuming so I
  2228.  show a spinning cursor to show the user I’m working.   Opening a resource
  2229.  fork may load resources mark preload.   To avoid this, I call SetResLoad
  2230.  to FALSE.  I bet you thought the Resource Manager was a free lunch.  Ha!
  2231.  Read Tech Note #203 for other reasons not to play with resources.
  2232.  
  2233.  BUG NOTE: While debugging this routine using heap scramble, I found that
  2234.  OpenResFile would not open the requested file.  I’m not sure if this is a
  2235.  problem with OpenResFile or SFGetFile.
  2236.  
  2237.  VERSION 1.1: The bug mentioned above was found.  The problem is that the 
  2238.  paramBlock happens to be a re-locatable block in the heap.  Passing the 
  2239.  de-reference ioNamePtr to HOpenResFile was de-referencing this 
  2240.  re-locatable paramBlock.  Since HOpenResFile moves memory, the namePtr 
  2241.  would no longer valid and thus HOpenResFile would fail.  Now I copy the 
  2242.  name out of the paramBlock and use the local variable in HOpenResFile.  
  2243.  This problem was fixed in System 7, which no longer passes a re-locatable 
  2244.  block to the file filter.  The new version allows for any resource file 
  2245.  to be opened  Because of this new feature, I only show the user files 
  2246.  that have a resource fork.}
  2247.  
  2248. CONST
  2249.     kShowIt =            FALSE;            {FALSE means I do not filter out...}
  2250.     kDoNotShowIt =        TRUE;                {the file and TRUE means that I do.}
  2251.  
  2252. VAR
  2253.     resFName:            Str255;
  2254.     oldTicks:            LONGINT;
  2255.     resRef, curRes:    INTEGER;
  2256.     theErr:                OSErr;
  2257.  
  2258. BEGIN
  2259.     oldTicks:= TickCount;
  2260.     SFFilter:= kDoNotShowIt;            {don’t show anything until I say so}
  2261.     IF gSndFilesOnly THEN BEGIN
  2262.         curRes:= CurResFile;
  2263.         resFName:= p^.ioNamePtr^;
  2264.         SetResLoad(FALSE);
  2265.         resRef:= HOpenResFile(p^.ioVRefNum, LongIntPtr(CurDirStore)^,
  2266.                                         resFName, fsRdPerm);
  2267.         IF (resRef <> -1) THEN BEGIN
  2268.             UseResFile(resRef);
  2269.             IF Count1Resources('snd ') > 0 THEN
  2270.                 SFFilter:= kShowIt;            {hey, we found a sound in here}
  2271.             CloseResFile(resRef);
  2272.         END;                                        {restore everything}
  2273.         SetResLoad(TRUE);
  2274.         UseResFile(curRes);
  2275.     END ELSE BEGIN
  2276.         IF p^.ioFlRLgLen > 0 THEN
  2277.             SFFilter:= kShowIt;
  2278.     END;
  2279.     RotateCursor(TickCount - oldTicks);
  2280. END; {SFFilter}
  2281.  
  2282. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2283. {$S Open}
  2284. FUNCTION SFGetHook(MySFItem: INTEGER; dialog: DialogPtr): INTEGER;
  2285.  
  2286. CONST
  2287.     kFirstTime =     -1;                    {item is -1 first time into hook}
  2288.     reDrawList =    101;                    {returning 101 as item number will
  2289.                                                  cause the file list to redraw}
  2290. VAR
  2291.     kind:                INTEGER;
  2292.     cntl:                ControlHandle;
  2293.     r:                    Rect;
  2294.  
  2295. BEGIN
  2296.     SFGetHook := MySFitem;
  2297.     GetDItem(dialog, rSndOnlyCheckBox, kind, Handle(cntl), r);
  2298.     CASE MySFItem OF
  2299.  
  2300.         kFirstTime: BEGIN
  2301.             IF gSndFilesOnly THEN
  2302.                 SetCtlValue(cntl, kCntlOn)
  2303.             ELSE
  2304.                 SetCtlValue(cntl, kCntlOff);
  2305.         END;
  2306.  
  2307.         rSndOnlyCheckBox: BEGIN
  2308.             IF GetCtlValue(cntl) = kCntlOff THEN BEGIN
  2309.                 SetCtlValue(cntl, kCntlOn);
  2310.                 gSndFilesOnly:= TRUE;
  2311.             END ELSE BEGIN
  2312.                 SetCtlValue(cntl, kCntlOff);
  2313.                 gSndFilesOnly:= FALSE;
  2314.             END;
  2315.             SFGetHook:= reDrawList;
  2316.         END;
  2317.     END;
  2318. END; {SFGetHook}
  2319.  
  2320. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2321. {$S Main}
  2322. PROCEDURE GetSoundDoc;
  2323.  
  2324. VAR
  2325.     reply:             SFReply;
  2326.     fileTypes:        SFTypeList;                            {not used, just a placeholder}
  2327.  
  2328. {VERSION 1.1: This routine used to be inside of OpenSoundDoc.  The 
  2329.  standard file code was removed to here in order to support opening 
  2330.  documents being open from the Finder.  I've switched to using a constant 
  2331.  for the topLeft point of the Standard File dialog.  It saves a few bytes 
  2332.  of code, so what the hell?  I found a cosmetic problem with the cursor 
  2333.  not being restored back to arrow after returning Standard File if there 
  2334.  was an error dialog shown immediately.  So, it is immediately set back to 
  2335.  the arrow.}
  2336.  
  2337. BEGIN
  2338.     SpinCursor(0);                                            {get the spinning cursor ready}
  2339.     SFPGetFile(Point(kSFTopLeft), '', @SFFilter, -1, fileTypes,
  2340.                     @SFGetHook, reply, rSFPGetFileDLOG, NIL);
  2341.     SetCursor(arrow);
  2342.     IF reply.good THEN
  2343.         OpenSoundDoc(@reply.fName, reply.VRefNum);
  2344. END; {GetSoundDoc}
  2345.  
  2346. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2347. {$S Main}
  2348. PROCEDURE DrawAboutWindow(window: WindowPtr);
  2349.  
  2350. {Draw the contents of the about window in response to an update event.  At
  2351.  this point, BeginUpdate has been called which sets the window’s visRgn to
  2352.  clip drawing only where it needs to be done.  I have some text to draw, an
  2353.  icon, a picture, and a default button with its outline.  If I have a color
  2354.  icon handle I’ll call PlotCIcon.  I offset the picture to draw to the
  2355.  right of the icon.  The text will appear in a rectangle as large as the
  2356.  window, but below the icon and above the button.  This allows me the
  2357.  change the text and if needed change the size of the window’s rectangle to
  2358.  compensate.  I won’t have to recompile any code.  Some people use dialogs
  2359.  because of this, but I’m demonstrating how it can be done without them.  I
  2360.  use UpdtControl to avoid needless drawing that happens with DrawControls.
  2361.  It not only runs faster but doesn’t flicker.}
  2362.  
  2363. VAR
  2364.     theRect:            Rect;
  2365.  
  2366. BEGIN
  2367.     PenNormal;
  2368.     SetRect(theRect, kIconLeft, kIconTop, kIconRight, kIconBot);
  2369.     IF AboutWPeek(window)^.iconIsColor THEN
  2370.         PlotCIcon(theRect, CIconHandle(AboutWPeek(window)^.appIcon))
  2371.     ELSE
  2372.         PlotIcon(theRect, AboutWPeek(window)^.appIcon);
  2373.  
  2374.     theRect:= PicHandle(AboutWPeek(window)^.appPict)^^.picFrame;
  2375.     OffsetRect(theRect, -theRect.left + kIconRight + kIconPictGap,
  2376.                               -theRect.top + kIconTop);
  2377.     DrawPicture(PicHandle(AboutWPeek(window)^.appPict), theRect);
  2378.  
  2379.     WITH window^.portRect DO
  2380.         SetRect(theRect, left, kIconBot, right, bottom - kDafaultButSizeH);
  2381.     InsetRect(theRect, kMsgInset, kMsgInset);
  2382.     HLock(AboutWPeek(window)^.comment);
  2383.     TextBox(Ptr(ORD(AboutWPeek(window)^.comment^) + 1),
  2384.                 LENGTH(StringHandle(AboutWPeek(window)^.comment)^^),
  2385.                 theRect, teJustCenter);
  2386.     HUnlock(AboutWPeek(window)^.comment);
  2387.  
  2388.     UpdtControl(window, window^.visRgn);
  2389.     DoButtonOutline(WindowPeek(window)^.controlList);
  2390. END; {DrawAboutWindow}
  2391.  
  2392. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2393. {$S Main}
  2394. PROCEDURE DoAbout;
  2395.  
  2396. {First thing to do is call KillSound to stop any sound in progress and
  2397.  close the status window.  If there’s enough memory available, I’ll play
  2398.  the about sound.  This is sound is asynchronous and will automatically be
  2399.  disposed of when completed.  There is an icon, taken from the bundle
  2400.  resources, and a picture.  The text is taken from a string resource.  It
  2401.  contains a couple variables just like ParamText would want.  I get the
  2402.  current name of the application from the AppParms.  This is the name of
  2403.  the application as specified by the user.  I read in my 'vers' resource
  2404.  to get the current version to be displayed in the window.  Read Tech Note
  2405.  189 for more details on the vers resource.  I think these are two
  2406.  important things to show in the about box.  These two portions of the text
  2407.  are put into place with my own version of ParamText.   I tried all of this
  2408.  with a standard dialog, but had trouble.  Sometimes the color icon didn’t
  2409.  show up.  Trying to center justify text with a statText item wasn’t really
  2410.  possible.  On the Mac SE, for some unknown reason, TESetJust failed to
  2411.  center the textH of the dialog.  I also found that this call would set the
  2412.  dialog’s text back to Chicago even after I had called TextFont.  So, I
  2413.  gave up and did everything myself.  This is a demonstration of how to
  2414.  create a dialog without using the Dialog Manager.}
  2415.  
  2416. VAR
  2417.     verNum,
  2418.     userName:        Str255;
  2419.     aboutPtr:        Ptr;
  2420.     aboutPeek:        AboutWPeek;
  2421.     control:            ControlHandle;
  2422.     hndl:                Handle;
  2423.     curVersion:        VersRecHndl;
  2424.     refNum:            INTEGER;
  2425.     theErr:            OSErr;
  2426.     ignore:            BOOLEAN;
  2427.  
  2428. BEGIN
  2429.     KillSound;
  2430.     aboutPtr:= NewPtrClear(SIZEOF(AboutWindow));
  2431.     IF aboutPtr <> NIL THEN BEGIN
  2432.         aboutPeek:= AboutWPeek(GetCenteredWindow(rAboutWindow, aboutPtr, WindowPtr(-1)));
  2433.         SetWRefCon(WindowPtr(aboutPeek), rAboutWindow);
  2434.         curVersion:= VersRecHndl(Get1Resource('vers', 1));
  2435.         IF curVersion <> NIL THEN
  2436.             verNum:= curVersion^^.shortVersion                {get version string}
  2437.         ELSE
  2438.             verNum:= '';                                            {at least initialize it}
  2439.         GetAppParms(userName, refNum, hndl);
  2440.         aboutPeek^.appPict:= Get1Resource('PICT', rAppPict);
  2441.         aboutPeek^.comment:= Get1Resource('STR ', rAboutText);
  2442.         aboutPeek^.appIcon:= NIL;
  2443.         aboutPeek^.iconIsColor:= TRUE;
  2444.         IF gMac.hasColorQD THEN
  2445.             aboutPeek^.appIcon:= Handle(GetCIcon(rMoofIcon));
  2446.         IF aboutPeek^.appIcon = NIL THEN BEGIN
  2447.             aboutPeek^.appIcon:= Get1Resource('ICON', rMoofIcon);
  2448.             aboutPeek^.iconIsColor:= FALSE;
  2449.         END;
  2450.         control:= GetNewControl(rAboutOkCntl, WindowPtr(aboutPeek));
  2451.  
  2452.         IF (aboutPeek^.appPict <> NIL) | (aboutPeek^.comment <> NIL)
  2453.          | (aboutPeek^.appIcon <> NIL) | (control <> NIL) THEN BEGIN
  2454.             HNoPurge(aboutPeek^.appPict);                        {must keep them around}
  2455.              HNoPurge(aboutPeek^.comment);
  2456.             HNoPurge(aboutPeek^.appIcon);
  2457.             MyParamText(StringHandle(aboutPeek^.comment), @userName, @verNum);
  2458.             IF NOT FailLowMemory(0) THEN
  2459.                 theErr:= AsynchSndPlay(Get1Resource('snd ', rMoofSound));
  2460.         END ELSE BEGIN                                                {couldn’t build window}
  2461.             DoErrorSound(1);
  2462.             ignore:= DoCloseWindow(WindowPtr(aboutPeek));
  2463.         END;
  2464.     END ELSE
  2465.         DoErrorSound(1);
  2466. END; {DoAbout}
  2467.  
  2468. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2469. {$S Main}
  2470. PROCEDURE PlaySelectedSnd(sndDoc: SndDocPeek; message: INTEGER);
  2471.  
  2472. {Get the selected sound and pass it to AsynchSndPlay or HyperSndPlay.  This
  2473.  depends on the normal flag.  HyperCard’s method is not normal.  This is
  2474.  the HyperCard version of playing a sound.  It resamples any sound to
  2475.  middle C.  If the resource is too large to fit in memory, I’ll get a NIL
  2476.  handle error from the Sound Unit.  It might be nice to test for this
  2477.  before calling the Sound Unit and telling the user they’re too low on
  2478.  memory, but the unit is robust enough and reports the error.  It’s
  2479.  important to call KillSound to dispose of any data that was
  2480.  allocated if an error were to occur.}
  2481.  
  2482. VAR
  2483.     sndHandle:    Handle;
  2484.     theErr:        OSErr;
  2485.  
  2486. BEGIN
  2487.     theErr:= GetSelection(sndDoc, sndHandle);
  2488.     IF theErr = noErr THEN BEGIN
  2489.         IF message = sPlayingMsg THEN
  2490.             theErr:= AsynchSndPlay(sndHandle)
  2491.         ELSE
  2492.             theErr:= HyperSndPlay(sndHandle);
  2493.     END;
  2494.     IF theErr = noErr THEN BEGIN
  2495.         sndDoc^.sndInUse:= TRUE;                    {this document has a snd in use}
  2496.         ShowStatusWindow(message);
  2497.     END ELSE BEGIN
  2498.         KillSound;
  2499.         AlertUser(theErr, sSoundErr);
  2500.     END;
  2501. END; {PlaySelectedSnd}
  2502.  
  2503. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2504. {$S Main}
  2505. PROCEDURE PlaySndSong(sndDoc: SndDocPeek; sndID: INTEGER);
  2506.  
  2507. {Given a sound resource ID, this will get my song resource and call the
  2508.  Sound Unit to use that sampled sound and song to play a tune.  This
  2509.  application will play one of two songs for sampled sounds.  If any error
  2510.  is encountered, I call KillSound to dispose of all data.}
  2511.  
  2512. VAR
  2513.     chan:             SndChannelPtr;
  2514.     sndInst,
  2515.     sndSong:            Handle;
  2516.     theErr:            OSErr;
  2517.  
  2518. BEGIN
  2519.     theErr:= GetSelection(sndDoc, sndInst);
  2520.     IF theErr = noErr THEN BEGIN
  2521.         sndSong:= Get1Resource('snd ', sndID);
  2522.         theErr:= ResError;                                {save any error}
  2523.         IF sndSong <> NIL THEN BEGIN
  2524.             theErr:= GetSampleChan(chan, kInitNone, sndInst);
  2525.             IF theErr = noErr THEN BEGIN
  2526.                 sndDoc^.sndInUse:= TRUE;                {this document has a snd in use}
  2527.                 theErr:= PlaySong(chan, sndSong);
  2528.             END;
  2529.         END;
  2530.     END;
  2531.     IF theErr = noErr THEN BEGIN
  2532.         IF sndID = rScaleSnd THEN
  2533.             ShowStatusWindow(sScaleMsg)
  2534.         ELSE                                                    {I can play scales or a melody}
  2535.             ShowStatusWindow(sMelodyMsg);
  2536.     END ELSE BEGIN                                            {catch any errors}
  2537.         KillSound;
  2538.         AlertUser(theErr, sSoundErr);
  2539.     END;
  2540. END; {PlaySndSong}
  2541.  
  2542. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2543. {$S Main}
  2544. PROCEDURE PlaySquareSong(sndID: INTEGER);
  2545.  
  2546. {Given a sound resource ID, this will get my song resource and call the
  2547.  Sound Unit to use the squareWaveSynth and song to play a tune.  I request
  2548.  the squareWaveSynth’s timbre (sounds like “tom burr”).  If any error is
  2549.  encountered, I call KillSound to dispose of all data.}
  2550.  
  2551. VAR
  2552.     theErr:            OSErr;
  2553.     sndSong:            Handle;
  2554.     chan:             SndChannelPtr;
  2555.  
  2556. BEGIN
  2557.     sndSong:= Get1Resource('snd ', sndID);
  2558.     IF (sndSong <> NIL) THEN BEGIN
  2559.         theErr:= GetSquareChan(chan, kPreferredTimbre);
  2560.         IF theErr = noErr THEN BEGIN
  2561.             theErr:= PlaySong(chan, sndSong);
  2562.             IF theErr = noErr THEN BEGIN
  2563.                 IF sndID = rScaleSnd THEN
  2564.                     ShowStatusWindow(sScaleMsg)
  2565.                 ELSE                                        {I play scales or a melody}
  2566.                     ShowStatusWindow(sMelodyMsg);
  2567.             END;
  2568.         END;
  2569.         IF theErr <> noErr THEN BEGIN                {catch any errors}
  2570.             KillSound;
  2571.             AlertUser(theErr, sSoundErr);
  2572.         END;
  2573.     END ELSE
  2574.         AlertUser(ResError, sResErr);            {I’ll return the resource error}
  2575. END; {PlaySquareSong}
  2576.  
  2577. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2578. {$S Main}
  2579. PROCEDURE PlaySquareTimbres;
  2580.  
  2581. {This is a demonstration of the squareWaveSynth’s tone qualities (or the lack
  2582.  there of).  This simply loops through timbres sending alternating frequency and
  2583.  rest commands.  Once all the sound commands have been sent, then I need to
  2584.  send a callBackCmd to signal the SoundUnit to dispose of the channel.  Well,
  2585.  actually the SoundUnit will set a global flag that the application will be
  2586.  polling for later in the event loop.  Once this happens, or if any errors
  2587.  are encountered along the way, KillSound will be called.  One very
  2588.  disappointing aspect to changing the timbre is that the Mac Plus or SE
  2589.  cannot handle this while a sound is heard.  The Apple Sound Chip can and
  2590.  if you wanted to remove the rests try this routine on a Mac II, for
  2591.  example, you can hear a continuous sound while the timbre changes.  Try
  2592.  this on a Mac Plus and you’ll hear garbage.  I’d show this myself, but how
  2593.  do I determine if the Mac has the ASC?
  2594.  
  2595.  BUG NOTE: There is problem when the final sound command is a freqDurationCmd.
  2596.  The frequency will continue to sound, looping forever, until a quietCmd is sent
  2597.  or the channel is disposed of.  To prevent unwanted looping, I send a
  2598.  quietCmd after all frequencies.}
  2599.  
  2600. VAR
  2601.     chan:             SndChannelPtr;
  2602.     timbre:            INTEGER;
  2603.     theErr:            OSErr;
  2604.  
  2605. BEGIN
  2606.     theErr:= GetSquareChan(chan, kPreferredTimbre);
  2607.     IF theErr = noErr THEN BEGIN
  2608.         ShowStatusWindow(sTimbresMsg);
  2609.         FOR timbre:= kSineWave TO kSquareWave DO BEGIN
  2610.             theErr:= SetSquareTimbre(chan, timbre, kWait);
  2611.             IF theErr = noErr THEN
  2612.                 theErr:= SendFreqDur(chan, kOneSecond DIV 2, kOctave7 + Akey);
  2613.             IF theErr = noErr THEN
  2614.                 theErr:= SendRest(chan, kOneSecond DIV 10);
  2615.             timbre:= timbre + 8;                            {skip a few more timbres}
  2616.             IF theErr <> noErr THEN                        {if there was an error...}
  2617.                 timbre:= kSquareWave + 1;                {get out of the loop}
  2618.         END;
  2619.     END;
  2620.     IF theErr = noErr THEN
  2621.         theErr:= SoundComplete(chan)
  2622.     ELSE BEGIN                                                {catch any errors}
  2623.         KillSound;
  2624.         AlertUser(theErr, sSoundErr);
  2625.     END;
  2626. END; {PlaySquareTimbres}
  2627.  
  2628. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2629. {$S Main}
  2630. PROCEDURE PlayWaveScale;
  2631.  
  2632. {This demonstrates the wave table synthesizers.  First thing to do is
  2633.  obtain a wave cycle and the 'snd ' resource containing a song to be
  2634.  played.  Then I’m ready to get the four wave channels and install the
  2635.  chosen wave.  Once the wave is installed into the channel I can dispose of
  2636.  the memory used to create the wave, since the Sound Manager will copy it
  2637.  to its internal buffers.  At this point I’m ready to play the song.  It’s
  2638.  not easy to hear four wave synths playing the same frequencies with the
  2639.  same wave table.  I was going to add a modifier to the channel that would
  2640.  transpose each channels frequency commands, but I found a bug.
  2641.  
  2642.  BUG NOTE: Installing a modifier to one of the wave table channels caused
  2643.  the channel to fail.  My normal sequence of events is this: I synchronize
  2644.  the four channels, send all the note commands, end this with the
  2645.  callBackCmd, and finally release the channels to play their queues.  When
  2646.  I added a modifier, the callBackCmd was the first command to be processed.
  2647.  This caused my completion routines to be called and before the channel
  2648.  made any sound it was disposed.  I tried this without the callBackCmd and
  2649.  the channel never processed any commands.
  2650.  
  2651.  BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  2652.  chip based Mac.  At least not so far with any System 6.0x releases.  This
  2653.  leaves the Mac Plus/SE without four tone polyphonic sound.}
  2654.  
  2655. VAR
  2656.     chan1, chan2,
  2657.     chan3, chan4:        SndChannelPtr;
  2658.     sndSong,
  2659.     waveHandle:            Handle;
  2660.     waveTablePtr:        Ptr;
  2661.     offSet:                LONGINT;
  2662.     sndType,
  2663.     waveLength:            INTEGER;
  2664.     theErr:                OSErr;
  2665.  
  2666. BEGIN
  2667.     IF (gMac.machineType IN [env512KE, envMacPlus, envSE])
  2668.      & (NOT HasNewSndMgr) THEN BEGIN
  2669.         AlertUser(badChannel, sWavesBroken);        {waves not available}
  2670.         EXIT(PlayWaveScale);                                {we’re out of here}
  2671.     END;
  2672.     sndSong:= Get1Resource('snd ', rScaleSnd);
  2673.     IF sndSong <> NIL THEN BEGIN
  2674.         waveHandle:= Get1Resource('snd ', rTenorVox);
  2675.         theErr:= HoldSnd(waveHandle);
  2676.         IF theErr = noErr THEN BEGIN
  2677.             offSet:= GetSndDataOffset(waveHandle, sndType, waveLength);
  2678.             waveTablePtr:= Ptr(ORD4(waveHandle^) + offSet);
  2679.             theErr:= GetWaveChans(chan1, chan2, chan3, chan4);
  2680.             IF theErr = noErr THEN BEGIN
  2681.                 theErr:= InstallWave(chan1, waveTablePtr, waveLength);
  2682.                 IF theErr = noErr THEN BEGIN
  2683.                     theErr:= InstallWave(chan2, waveTablePtr, waveLength);
  2684.                     IF theErr = noErr THEN BEGIN
  2685.                         theErr:= InstallWave(chan3, waveTablePtr, waveLength);
  2686.                         IF theErr = noErr THEN
  2687.                             theErr:= InstallWave(chan4, waveTablePtr, waveLength);
  2688.                     END;
  2689.                 END;
  2690.             END;
  2691.             HUnlock(waveHandle);
  2692.             HPurge(waveHandle);
  2693.             IF theErr = noErr THEN
  2694.                 theErr:= Play4Waves(chan1, chan2, chan3, chan4,
  2695.                                           sndSong, sndSong, sndSong, sndSong);
  2696.             IF theErr = noErr THEN
  2697.                 ShowStatusWindow(sScaleMsg)
  2698.             ELSE BEGIN                                {catch any sound unit errors}
  2699.                 KillSound;
  2700.                 AlertUser(theErr, sSoundErr);
  2701.             END;
  2702.         END ELSE
  2703.             AlertUser(theErr, sResErr);        {couldn’t get waveHandle}
  2704.     END ELSE
  2705.         AlertUser(ResError, sResErr);            {couldn’t get song}
  2706. END;
  2707.  
  2708. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2709. {$S Main}
  2710. FUNCTION GetSndSongs(sndSongID1, sndSongID2, sndSongID3, sndSongID4: INTEGER;
  2711.                             VAR sndSong1, sndSong2, sndSong3, sndSong4: Handle): OSErr;
  2712.  
  2713. {This is a utility routine used to obtain the four snd resources that
  2714.  contain parts of a song.  Nothing much to do other then get the resource
  2715.  and do error checking.}
  2716.  
  2717. BEGIN
  2718.     GetSndSongs:= noErr;                                        {initialize result}
  2719.     sndSong1:= Get1Resource('snd ', sndSongID1);     {get all the snds}
  2720.     IF sndSong1 <> NIL THEN BEGIN
  2721.         sndSong2:= Get1Resource('snd ', sndSongID2);
  2722.         IF sndSong2 <> NIL THEN BEGIN
  2723.             sndSong3:= Get1Resource('snd ', sndSongID3);
  2724.             IF sndSong3 <> NIL THEN
  2725.                 sndSong4:= Get1Resource('snd ', sndSongID4);
  2726.         END;
  2727.     END;
  2728.     IF (sndSong1 = NIL) | (sndSong2 = NIL)
  2729.      | (sndSong3 = NIL) | (sndSong4 = NIL) THEN
  2730.         GetSndSongs:= ResErr;                                {return resource error}
  2731. END;
  2732.  
  2733. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2734. {$S Main}
  2735. FUNCTION InstallWaveSnds(chan1, chan2, chan3, chan4: SndChannelPtr;
  2736.                                     waveID1, waveID2, waveID3, waveID4: INTEGER): OSErr;
  2737.  
  2738. {This routine is a utility I’m using to prepare four wave table channels.
  2739.  First thing to do is obtain a wave table data I stored in a set of 'snd '
  2740.  resources.  Then I’m ready to install these wave tables into the four wave
  2741.  channels.  Once the waves are installed into the channel I can dispose of
  2742.  the memory used to create each wave, since the Sound Manager will copy
  2743.  them to its internal buffers.  At this point the channels are ready to
  2744.  play sounds.}
  2745.  
  2746. VAR
  2747.     waveSnd1, waveSnd2,
  2748.     waveSnd3, waveSnd4:    Handle;
  2749.     wavePtr:                    Ptr;
  2750.     offSet:                    LONGINT;
  2751.     waveLgth, sndType:    INTEGER;
  2752.     theErr:                    OSErr;
  2753.  
  2754. BEGIN
  2755.     waveSnd1:= Get1Resource('snd ', waveID1);        {get em and hold em down}
  2756.     theErr:= HoldSnd(waveSnd1);
  2757.     IF theErr = noErr THEN BEGIN
  2758.         waveSnd2:= Get1Resource('snd ', waveID2);
  2759.         theErr:= HoldSnd(waveSnd2);
  2760.         IF theErr = noErr THEN BEGIN
  2761.             waveSnd3:= Get1Resource('snd ', waveID3);
  2762.             theErr:= HoldSnd(waveSnd3);
  2763.             IF theErr = noErr THEN BEGIN
  2764.                 waveSnd4:= Get1Resource('snd ', waveID4);
  2765.                 theErr:= HoldSnd(waveSnd4);
  2766.             END;
  2767.         END;
  2768.     END;
  2769.     InstallWaveSnds:= theErr;                            {return the error}
  2770.     IF theErr <> noErr THEN
  2771.         EXIT(InstallWaveSnds);                            {we’re out of here}
  2772.                                                                 {catch the waves}
  2773.     offSet:= GetSndDataOffset(waveSnd1, sndType, waveLgth);
  2774.     wavePtr:= Ptr(ORD4(waveSnd1^) + offSet);
  2775.     theErr:= InstallWave(chan1, wavePtr, waveLgth);
  2776.     IF theErr = noErr THEN BEGIN
  2777.         offSet:= GetSndDataOffset(waveSnd2, sndType, waveLgth);
  2778.         wavePtr:= Ptr(ORD4(waveSnd2^) + offSet);
  2779.         theErr:= InstallWave(chan2, wavePtr, waveLgth);
  2780.         IF theErr = noErr THEN BEGIN
  2781.             offSet:= GetSndDataOffset(waveSnd3, sndType, waveLgth);
  2782.             wavePtr:= Ptr(ORD4(waveSnd3^) + offSet);
  2783.             theErr:= InstallWave(chan3, wavePtr, waveLgth);
  2784.             IF theErr = noErr THEN BEGIN
  2785.                 offSet:= GetSndDataOffset(waveSnd4, sndType, waveLgth);
  2786.                 wavePtr:= Ptr(ORD4(waveSnd4^) + offSet);
  2787.                 theErr:= InstallWave(chan4, wavePtr, waveLgth);
  2788.             END;
  2789.         END;
  2790.     END;
  2791.     HUnlock(waveSnd1);                                    {done with resources}
  2792.     HPurge(waveSnd1);
  2793.     HUnlock(waveSnd2);
  2794.     HPurge(waveSnd2);
  2795.     HUnlock(waveSnd3);
  2796.     HPurge(waveSnd3);
  2797.     HUnlock(waveSnd4);
  2798.     HPurge(waveSnd4);
  2799.     InstallWaveSnds:= theErr;                            {return the error}
  2800. END;
  2801.  
  2802. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2803. {$S Main}
  2804. PROCEDURE PlayWaveMelody;
  2805.  
  2806. {This is the demonstration of the wave table synthesizers.  This will get
  2807.  four snd resources that contain parts to a song.  Then I get the four wave
  2808.  table channels.  With these four channels, I install two other snd
  2809.  resources that contain wave table data.  Once the four songs, four
  2810.  channels, and two wave tables are ready then I play the song.
  2811.  
  2812.  BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  2813.  chip based Mac.  At least not so far with any System 6.0x release.  This
  2814.  leaves the Mac Plus/SE without four tone polyphonic sound.}
  2815.  
  2816. VAR
  2817.     sndSong1, sndSong2,
  2818.     sndSong3, sndSong4:    Handle;
  2819.     chan1, chan2,
  2820.     chan3, chan4:            SndChannelPtr;
  2821.     theErr:                    OSErr;
  2822.  
  2823. BEGIN
  2824.     theErr:= noErr;
  2825.     IF (gMac.machineType IN [env512KE, envMacPlus, envSE])
  2826.      & (NOT HasNewSndMgr) THEN BEGIN
  2827.         AlertUser(badChannel, sWavesBroken);            {waves not available}
  2828.         EXIT(PlayWaveMelody);                                {we’re out of here}
  2829.     END;
  2830.     theErr:= GetSndSongs(rMelodyPart1, rMelodyPart2, rMelodyPart3, rMelodyPart4,
  2831.                                 sndSong1, sndSong2, sndSong3, sndSong4);
  2832.     IF theErr <> noErr THEN BEGIN
  2833.         AlertUser(theErr, sResErr);                {return the error}
  2834.         EXIT(PlayWaveMelody);
  2835.     END;
  2836.     theErr:= GetWaveChans(chan1, chan2, chan3, chan4);
  2837.     IF theErr = noErr THEN BEGIN
  2838.         theErr:= InstallWaveSnds(chan1, chan2, chan3, chan4,
  2839.                                     rWaveMelody, rWaveHarmony, rWaveHarmony, rWaveHarmony);
  2840.         IF theErr = noErr THEN
  2841.             theErr:= Play4Waves(chan1, chan2, chan3, chan4,
  2842.                                           sndSong1, sndSong2, sndSong3, sndSong4);
  2843.     END;
  2844.     IF theErr = noErr THEN
  2845.         ShowStatusWindow(sMelodyMsg)
  2846.     ELSE BEGIN                                        {catch any errors}
  2847.         KillSound;
  2848.         AlertUser(theErr, sSoundErr);
  2849.     END;
  2850. END;
  2851.  
  2852. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2853. {$S Main}
  2854. PROCEDURE PlayWaveSATB;
  2855.  
  2856. {This is the demonstration of the wave table synthesizers.  This will get
  2857.  four snd resources that contain parts to a song.  Then I get the four wave
  2858.  table channels.  With these four channels, I install four other snd resources
  2859.  that contain wave table data.  Once the four songs, four channels, and
  2860.  four wave tables are ready then I play the song.  By the way, SATB stands
  2861.  for Soprano, Alto, Tenor, and Bass.  It’s standard music-speak.
  2862.  
  2863.  BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  2864.  chip based Mac.  At least not so far with any System 6.0x release.  This
  2865.  leaves the Mac Plus/SE without four tone polyphonic sound.}
  2866.  
  2867. VAR
  2868.     sndSong1, sndSong2,
  2869.     sndSong3, sndSong4:    Handle;
  2870.     chan1, chan2,
  2871.     chan3, chan4:            SndChannelPtr;
  2872.     theErr:                    OSErr;
  2873.  
  2874. BEGIN
  2875.     theErr:= noErr;
  2876.     IF (gMac.machineType IN [env512KE, envMacPlus, envSE])
  2877.      & (NOT HasNewSndMgr) THEN BEGIN
  2878.         AlertUser(badChannel, sWavesBroken);            {waves not available}
  2879.         EXIT(PlayWaveSATB);                                    {we’re out of here}
  2880.     END;
  2881.     theErr:= GetSndSongs(rCounterPt1, rCounterPt2, rCounterPt3, rCounterPt4,
  2882.                                 sndSong1, sndSong2, sndSong3, sndSong4);
  2883.     IF theErr <> noErr THEN BEGIN
  2884.         AlertUser(theErr, sResErr);                        {return the error}
  2885.         EXIT(PlayWaveSATB);
  2886.     END;
  2887.     theErr:= GetWaveChans(chan1, chan2, chan3, chan4);
  2888.     IF theErr = noErr THEN BEGIN
  2889.         theErr:= InstallWaveSnds(chan1, chan2, chan3, chan4,
  2890.                                             rSopranoVox, rAltoVox, rTenorVox, rBassVox);
  2891.         IF theErr = noErr THEN
  2892.             theErr:= Play4Waves(chan1, chan2, chan3, chan4,
  2893.                                           sndSong1, sndSong2, sndSong3, sndSong4);
  2894.     END;
  2895.     IF theErr = noErr THEN
  2896.         ShowStatusWindow(sCounterPtMsg)
  2897.     ELSE BEGIN                                                    {catch any errors}
  2898.         KillSound;
  2899.         AlertUser(theErr, sSoundErr);
  2900.     END;
  2901. END;
  2902.  
  2903.  
  2904. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2905. {$S Main}
  2906. PROCEDURE DefaultOutline(window: WindowPtr; theItem: INTEGER);
  2907.  
  2908. {VERSION 1.1:  This is just one of the reasons I hate the Dialog Manager.  
  2909.  I needed a simple dialog to ask the user for a name for their new sound.  
  2910.  To do this, I only needed a simple dialog with two buttons and an 
  2911.  editable text item.  Since the ModalDialog will not draw an outline 
  2912.  around the default item, I then needed an userItem.  This is the really 
  2913.  stupid part. The userItem is only there just to get a chance to draw an 
  2914.  outline around the default button.  It has no other purpose.  It is not 
  2915.  visible, not does it get any user interaction what so ever.  It's just a 
  2916.  pain in the ass.}
  2917.  
  2918. VAR
  2919.     itemHndl:            Handle;
  2920.     itemRect:            Rect;
  2921.     kind:                    INTEGER;
  2922.  
  2923. BEGIN
  2924.     GetDItem(DialogPtr(window), ok, kind, itemHndl, itemRect);
  2925.     DoButtonOutline(ControlHandle(itemHndl));
  2926. END;
  2927.  
  2928. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2929. {$S Main}
  2930. PROCEDURE GetSndName(VAR sndName: Str255);
  2931.  
  2932. {VERSION 1.1:  Show a dialog asking the user to name their new sound 
  2933.  resource.  I need to outline the default button, so I have to install an 
  2934.  userItem setting its drawing procedure to do the outline around a 
  2935.  different item altogether.  The Dialog Manager really bugs me.}
  2936.  
  2937. VAR
  2938.     dialog:                DialogPtr;
  2939.     itemHndl:            Handle;
  2940.     itemRect:            Rect;
  2941.     kind:                    INTEGER;
  2942.     theItem:                INTEGER;
  2943.  
  2944. BEGIN
  2945.     dialog:= GetCenteredDialog(rGetNameDLOG, NIL, WindowPtr(-1));
  2946.     GetDItem(dialog, rUserItem, kind, itemHndl, itemRect);
  2947.     SetDItem(dialog, rUserItem, kind, @DefaultOutline, itemRect);
  2948.     REPEAT
  2949.         ModalDialog(NIL, theItem);
  2950.     UNTIL (theItem = ok) | (theItem = cancel);
  2951.     IF theItem = ok THEN BEGIN
  2952.         GetDItem(dialog, rNameItem, kind, itemHndl, itemRect);
  2953.         GetIText(itemHndl, sndName);
  2954.     END ELSE
  2955.         sndName:= '';
  2956.     DisposDialog(dialog);
  2957. END;
  2958.  
  2959. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  2960. {$S Main}
  2961. FUNCTION AddSnd(sndDoc: SndDocPeek; sndNamePtr: StringPtr; sndHndl: Handle): OSErr;
  2962.  
  2963. {VERSION 1.1:  This routine adds the given snd resource to the file and 
  2964.  document. First thing to do is find a proper resource ID for the 'snd '.  
  2965.  There is a reserved range for them, didn't you read the documentation?  
  2966.  Once this new resource is added then I update the file and re-build the 
  2967.  list of sounds.  This is necessary since the list must be in the same 
  2968.  order as the sounds are in the file.  I ignore the error returned by 
  2969.  InitSndList, since the chances of it failing at this point are slim.  If 
  2970.  anything is wrong with the list, then the rest of this application is 
  2971.  robust enough to handle a resource problem.  The user would have to close 
  2972.  the document and attempt to open it again.  If adding the resources 
  2973.  works, but updating the file fails then I will remove it.  This keeps the 
  2974.  document consistent with the file.}
  2975.  
  2976. VAR
  2977.     resID:            INTEGER;
  2978.     theErr:            OSErr;
  2979.     ignore:                INTEGER;
  2980.  
  2981. BEGIN
  2982.     UseResFile(sndDoc^.resFile);                {put our resource in the right file}
  2983.     REPEAT
  2984.         resID:= Unique1ID('snd ');
  2985.     UNTIL resID > kSystemSndRange;
  2986.     AddResource(sndHndl, 'snd ', resID, sndNamePtr^);
  2987.     theErr:= ResError;
  2988.     UseResFile(gAppResRef);                        {restore our resource file}
  2989.     IF theErr = noErr THEN BEGIN
  2990.         UpdateResFile(sndDoc^.resFile);        {update the file}
  2991.         theErr:= ResError;
  2992.         IF theErr = noErr THEN BEGIN
  2993.             ignore:= FlushVol(nil, sndDoc^.vRefNum);
  2994.             LDelRow(0, 0, sndDoc^.list);        {delete all the rows}
  2995.             ignore:= InitSndList(sndDoc);        {re-create the list}
  2996.             SelectSndCell(sndDoc, resID);        {select the new snd}
  2997.         END ELSE
  2998.             RmveResource(sndHndl);                {couldn't add it, update failed}
  2999.     END;
  3000.     AddSnd:= theErr;
  3001. END;
  3002.  
  3003. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3004. {$S Main}
  3005. PROCEDURE ClearSnd(sndDoc: SndDocPeek);
  3006.  
  3007. {VERSION 1.1:  This routine has one tricky aspect involving the Resource 
  3008.  Manager and removing a resource.  There's a catch.  I want the document 
  3009.  to always reflect the contents of the file on disk.  In other words, 
  3010.  InitSndList depends on UpdateResFile returning noErr.  If the file is 
  3011.  locked, then removing a resource shouldn't be allowed but RmveResource 
  3012.  will return noErr even if the file cannot be updated.  This is a 
  3013.  "feature" since the user may unlock the volume after removing the 
  3014.  resource and then UpdateResFile would work.  If RmveResource succeeds, 
  3015.  but UpdateResFile fails then the resource map in memory will be 
  3016.  inconsistent with what's on disk.  If the user then closed the document 
  3017.  and opened it again, the resource they just removed would magically still 
  3018.  be there.  The basic problem is that it is difficult to determine if a 
  3019.  given file will really allow write access.  There's at least three 
  3020.  situations to check: a locked file, a locked volume, or an AppleShare 
  3021.  folder privileges issue.  The ideal, and probably the best, solution 
  3022.  would be to deselect the edit commands from the user for a read-only 
  3023.  file.  This would involve lots of File Manager calls every time the user 
  3024.  selects a menu command.  (If you thought that GetFCBInfo would tell you 
  3025.  this, you're wrong.  You can have write permission to a file that is on a 
  3026.  locked volume.)  Additionally, the user needs to see that the reason the 
  3027.  edit menu doesn't work is because the file is read-only which would 
  3028.  require another feature to be added with lots more code.  This is why I 
  3029.  call ChangedResource before any other Resource Manager calls.  
  3030.  ChangedResource will determine if the resource can be written to disk.  
  3031.  If not, then it returns an error which is exactly what I wanted to know 
  3032.  in the first place.  I want to flush the cache to keep the disk's 
  3033.  resource map consistent with the resource data.  Otherwise, a crash could 
  3034.  occur the resource fork might be damaged and the file has to be repaired 
  3035.  (if possible) or deleted.  I'm ignoring the InitSndList result.  At this 
  3036.  stage, there's only a slim chance the list couldn't be re-built.  If it 
  3037.  does fail, the file should be closed.
  3038.  
  3039.  A tip to the reader: dispose of as much memory as possible before calling 
  3040.  UpdateResFile.  This makes it faster.  UpdateResFile will not purge any 
  3041.  memory, but only attempts to use the available space.  If there's little 
  3042.  free space then UpdateResFile will run really slow.}
  3043.  
  3044. VAR
  3045.     resFName:            Str255;
  3046.     sndHndl:                Handle;
  3047.     theErr, openErr:    OSErr;
  3048.     ignore:                INTEGER;
  3049.     closed:                BOOLEAN;
  3050.     
  3051. BEGIN
  3052.     theErr:= GetSelection(sndDoc, sndHndl);        {get the resource to remove}
  3053.     IF theErr = noErr THEN BEGIN
  3054.         ChangedResource(sndHndl);                        {can we change the file?}
  3055.         theErr:= ResError;                                {save the error result}
  3056.         IF theErr = noErr THEN BEGIN
  3057.             UseResFile(sndDoc^.resFile);                {use the right resource file}
  3058.             RmveResource(sndHndl);                        {remove that sucker}
  3059.             theErr:= ResError;                            {save the error result}
  3060.             UseResFile(gAppResRef);                        {restore our resource file}
  3061.             IF theErr = noErr THEN BEGIN
  3062.                 DisposHandle(sndHndl);                    {get rid of the memory}
  3063.                 UpdateResFile(sndDoc^.resFile);        {update the file}
  3064.                 theErr:= ResError;                        {save the error result}
  3065.                 IF theErr = noErr THEN
  3066.                     ignore:= FlushVol(nil, sndDoc^.vRefNum);
  3067.                 LDelRow(0, 0, sndDoc^.list);            {delete all the rows}
  3068.                 ignore:= InitSndList(sndDoc);            {re-create the list}
  3069.                 SelectNextCell(sndDoc^.list, TRUE); {select the first cell}
  3070.                 ActivateSndCntls(sndDoc);                {may not be any sounds left}
  3071.             END;
  3072.         END;
  3073.     END;
  3074.     IF theErr <> noErr THEN
  3075.         AlertUser(theErr, sEditErr);
  3076. END; {ClearSnd}
  3077.  
  3078. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3079. {$S Main}
  3080. PROCEDURE DoRecordSound(sndDoc: SndDocPeek);
  3081.  
  3082. {VERSION 1.1:  This routine will create a handle and record sound into it.  
  3083.  A new sound will prompt the user for a name to add it to the document.  
  3084.  The Sound Input Manager will re-size this handle to be as small as 
  3085.  possible to contain only the samples recorded.  You can pass sndHandl = 
  3086.  NIL to SndRecord, which will cause the Sound Input Manager to create a 
  3087.  handle for you.  If adding the new sound is successful, the new resource 
  3088.  handle is marked purgeable, because I only use them temporally and they 
  3089.  tend to be large.  I have to set the sndHandle variable to NIL in this 
  3090.  case since it is now belongs to the Resource Manager and I don't want to 
  3091.  dispose of it in the error handling code.  The choice of recording 
  3092.  quality wasn't given to the user.  Typically, users would only be 
  3093.  confused by the question of "what compression ratio do you prefer?"  As
  3094.  a power user option, it would be nice to let the user set the rate.  Be
  3095.  careful since this is a user interface issue, and Apple expects to see
  3096.  lots of Sound Input features in applications.}
  3097.  
  3098. VAR
  3099.     sndName:                Str255;
  3100.     total:                LONGINT;
  3101.     contig:                LONGINT;
  3102.     sndHandle:            Handle;
  3103.     theErr:                OSErr;
  3104.  
  3105. BEGIN
  3106.     KillSound;
  3107.     PurgeSpace(total, contig);
  3108.     sndHandle:= NewHandle(contig - kMinSpace);
  3109.     IF sndHandle <> NIL THEN BEGIN
  3110.         theErr:= SndRecord(NIL, Point(kSFTopLeft), siBestQuality, sndHandle);
  3111.         IF theErr = noErr THEN BEGIN
  3112.             GetSndName(sndName);
  3113.             theErr:= AddSnd(sndDoc, @sndName, sndHandle);
  3114.             IF theErr = noErr THEN BEGIN
  3115.                 HPurge(sndHandle);
  3116.                 sndHandle:= NIL;
  3117.             END;
  3118.         END;
  3119.     END ELSE
  3120.         theErr:= MemError;
  3121.     IF sndHandle <> NIL THEN
  3122.         DisposHandle(sndHandle);
  3123.     IF (theErr <> noErr) & (theErr <> userCanceledErr) THEN
  3124.         AlertUser(theErr, sSoundErr);
  3125. END;
  3126.  
  3127. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3128. {$S Main}
  3129. PROCEDURE AdjustMenus;
  3130.  
  3131. {Enable and disable menus based on the current state.  The user can only
  3132.  select enabled menu items so I set up all the menu items before calling
  3133.  MenuSelect or MenuKey, since these are the only times that a menu item
  3134.  can be selected. Note that MenuSelect is also the only time the user will
  3135.  see menu items. This approach to deciding what enable/disable state a menu
  3136.  item has the advantage of concentrating all the decision making in one
  3137.  routine, as opposed to being spread throughout the application.  Other
  3138.  application designs may take a different approach that may or may not be
  3139.  just as valid.}
  3140.  
  3141. VAR
  3142.      menu:            MenuHandle;
  3143.     window:        WindowPtr;
  3144.     allowEdit:    BOOLEAN;
  3145.  
  3146. BEGIN
  3147.     window:= FrontWindow;
  3148.  
  3149.     menu:= GetMHandle(mFile);                        {the File menu and items}
  3150.     IF IsDAWindow(window) | IsDocWindow(window) THEN
  3151.         EnableItem(menu, iClose)
  3152.     ELSE
  3153.         DisableItem(menu, iClose);
  3154.  
  3155.     menu:= GetMHandle(mEdit);                        {the Edit menu and items}
  3156.     allowEdit:= IsDAWindow(window);
  3157.     IF allowEdit THEN                                    {check the undo item}
  3158.         EnableItem(menu, iUndo)
  3159.     ELSE
  3160.         DisableItem(menu, iUndo);
  3161.  
  3162.     IF IsDocWindow(window) THEN BEGIN            {handle the other edit items}
  3163.         allowEdit:= HasSelection(SndDocPeek(window)) | allowEdit;
  3164.         EnableItem(menu, iPaste);
  3165.     END ELSE
  3166.         DisableItem(menu, iPaste);
  3167.         
  3168.     IF allowEdit THEN BEGIN
  3169.         EnableItem(menu, iCut);
  3170.         EnableItem(menu, iCopy);
  3171.         EnableItem(menu, iClear);
  3172.     END ELSE BEGIN
  3173.         DisableItem(menu, iCut);
  3174.         DisableItem(menu, iCopy);
  3175.         DisableItem(menu, iClear);
  3176.     END;
  3177. END; {AdjustMenus}
  3178.  
  3179. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3180. {$S Main}
  3181. PROCEDURE CopySnd(sndDoc: SndDocPeek);
  3182.  
  3183. {VERSION 1.1:  Get the currently selected item and copy it to the 
  3184.  clipboard.  I want to also save the name for this resource, so I add a 
  3185.  string type to the clipboard as well.}
  3186.  
  3187. VAR
  3188.     sndName:            Str255;
  3189.     rType:            ResType;
  3190.     scrapLen:        LONGINT;
  3191.     id:                INTEGER;
  3192.     sndHndl:            Handle;
  3193.     theErr:            OSErr;
  3194.     
  3195. BEGIN
  3196.     theErr:= GetSelection(sndDoc, sndHndl);
  3197.     IF theErr = noErr THEN BEGIN
  3198.         GetResInfo(sndHndl, id, rType, sndName);
  3199.         scrapLen:= ZeroScrap;                        {ignoring the result}
  3200.         theErr:= PutScrap(LENGTH(sndName) + 1, 'STR ', @sndName);
  3201.         HLock(sndHndl);
  3202.         theErr:= PutScrap(GetHandleSize(sndHndl), 'snd ', sndHndl^);
  3203.         HUnlock(sndHndl);
  3204.         HPurge(sndHndl);
  3205.     END;
  3206.     IF theErr <> noErr THEN
  3207.         AlertUser(theErr, sEditErr);
  3208. END;
  3209.  
  3210. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3211. {$S Main}
  3212. PROCEDURE CutSnd(sndDoc: SndDocPeek);
  3213.  
  3214. {VERSION 1.1:  Copy the selection and then delete it.}
  3215.  
  3216. BEGIN
  3217.     CopySnd(sndDoc);
  3218.     ClearSnd(sndDoc);
  3219. END;
  3220.  
  3221. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3222. {$S Main}
  3223. PROCEDURE PasteSnd(sndDoc: SndDocPeek);
  3224.  
  3225. {VERSION 1.1:  This routine will create a new resource into the file 
  3226.  containing the clipboard's sound data.  A name is attempted to be found 
  3227.  by first checking for the string type in the scrap.  This application 
  3228.  will always put both a string and a sound together on the clipboard.  But 
  3229.  if the user copied a sound from the Sound cdev, ResEdit, or by some other 
  3230.  method then I'll ask the user for a new name.  If adding the new resource 
  3231.  is successful, then I mark the resource as purgeable and set the sndHndl 
  3232.  variable to NIL.  The Resource Manager then owns the handle and I don't 
  3233.  want my error handling to dispose of this new handle.}
  3234.  
  3235. VAR
  3236.     sndName:            Str255;
  3237.     sndNameHndl:    StringHandle;
  3238.     offset:            LONGINT;
  3239.     scrapLen:        LONGINT;
  3240.     sndHndl:            Handle;
  3241.     theErr:            OSErr;
  3242.  
  3243. BEGIN
  3244.     sndHndl:= NewHandle(0);
  3245.     sndNameHndl:= NewString('');
  3246.     theErr:= MemError;
  3247.     scrapLen:= GetScrap(Handle(sndNameHndl), 'STR ', offset);
  3248.     scrapLen:= GetScrap(sndHndl, 'snd ', offset);
  3249.     IF scrapLen > 0 THEN BEGIN
  3250.         IF sndNameHndl <> NIL THEN
  3251.             sndName:= sndNameHndl^^
  3252.         ELSE
  3253.             sndName:= '';
  3254.         IF sndName = '' THEN
  3255.             GetSndName(sndName);
  3256.         theErr:= AddSnd(sndDoc, @sndName , sndHndl);
  3257.         IF theErr = noErr THEN BEGIN
  3258.             HPurge(sndHndl);
  3259.             sndHndl:= NIL;                                        {done with handle}
  3260.             ActivateSndCntls(sndDoc);
  3261.         END;
  3262.     END ELSE
  3263.         theErr:= scrapLen;
  3264.  
  3265.     IF sndHndl <> NIL THEN
  3266.         DisposHandle(sndHndl);
  3267.     IF sndNameHndl <> NIL THEN
  3268.         DisposHandle(Handle(sndNameHndl));
  3269.     IF theErr <> noErr THEN
  3270.         AlertUser(theErr, sEditErr);
  3271. END;
  3272.  
  3273. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3274. {$S Main}
  3275. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  3276.  
  3277. {This is called when an item is chosen from the menu bar (after calling
  3278.  MenuSelect or MenuKey). It performs the right operation for each command.
  3279.  It is good to have both the result of MenuSelect and MenuKey go to
  3280.  one routine like this to keep everything organized.
  3281.  
  3282.  VERSION 1.1:  Supporting the edit commands for snd resources.}
  3283.  
  3284. VAR
  3285.     window:                WindowPtr;
  3286.     menuID, menuItem,                        {resource ID and item of the selected menu}
  3287.     daRefNum:            INTEGER;
  3288.     daName:                Str255;
  3289.     ignore:                BOOLEAN;
  3290.  
  3291. BEGIN
  3292.     menuID:= HiWrd(menuResult);        {use MPW’s built-ins for efficiency...}
  3293.     menuItem:= LoWrd(menuResult);        {to get menu item number and menu number}
  3294.     CASE menuID OF
  3295.  
  3296.         mApple:
  3297.             CASE menuItem OF
  3298.                 iAbout:                        {bring up alert for About}
  3299.                     DoAbout;
  3300.                 OTHERWISE BEGIN            {all non-About items in this menu are DAs}
  3301.                     GetItem(GetMHandle(mApple), menuItem, daName);
  3302.                     daRefNum:= OpenDeskAcc(daName);
  3303.                 END;
  3304.             END;
  3305.  
  3306.         mFile:
  3307.             CASE menuItem OF
  3308.                 iNew:
  3309.                     NewSoundDoc;
  3310.                 iOpen:
  3311.                     GetSoundDoc;
  3312.                 iClose:
  3313.                     ignore:= DoCloseWindow(FrontWindow); {I don’t care if cancelled}
  3314.                 iQuit:
  3315.                     Terminate;
  3316.             END;
  3317.  
  3318.         mEdit: BEGIN                        {call SystemEdit for DA editing & MultiFinder}
  3319.             IF NOT SystemEdit(menuItem - 1) THEN BEGIN {since I don’t do any editing}
  3320.                 window:= FrontWindow;
  3321.                 IF IsDocWindow(window) THEN BEGIN
  3322.                     CASE menuItem OF
  3323.                         
  3324.                         iCut:
  3325.                             CutSnd(SndDocPeek(window));
  3326.                             
  3327.                         iCopy:
  3328.                             CopySnd(SndDocPeek(window));
  3329.                                 
  3330.                         iPaste:
  3331.                             PasteSnd(SndDocPeek(window));
  3332.                             
  3333.                         iClear:
  3334.                             ClearSnd(SndDocPeek(window));
  3335.  
  3336.                     END;
  3337.                 END;
  3338.             END;
  3339.         END;
  3340.  
  3341.         mDemos:
  3342.             CASE menuItem OF
  3343.  
  3344.                 iSquareScale:
  3345.                     PlaySquareSong(rScaleSnd);
  3346.  
  3347.                 iSquareMelody:
  3348.                     PlaySquareSong(rMelodyPart1);
  3349.  
  3350.                 iSquareTimbre:
  3351.                     PlaySquareTimbres;
  3352.  
  3353.                 iWaveScale:
  3354.                     PlayWaveScale;
  3355.  
  3356.                 iWaveMelody:
  3357.                     PlayWaveMelody;
  3358.  
  3359.                 iWaveSATB:
  3360.                     PlayWaveSATB;
  3361.  
  3362.             END; {CASE menuItem OF}
  3363.  
  3364.     END; {CASE menuID OF}
  3365.     HiliteMenu(0);                        {unhighlight what MenuSelect or MenuKey hilited}
  3366. END; {DoMenuCommand}
  3367.  
  3368. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3369. {$S Main}
  3370. PROCEDURE DrawSndWindow(window: WindowPtr);
  3371.  
  3372. {Draw the contents of the application window in response to an update
  3373.  event.  At this point, BeginUpdate has been called which sets the window’s
  3374.  visRgn to clip drawing only where it needs to be done.  I have the
  3375.  controls to draw, a list to update, and a default button to outline.  I
  3376.  use UpdtControl to avoid needless drawing that happens with DrawControls.
  3377.  It not only runs faster but doesn’t flicker.}
  3378.  
  3379.  VAR
  3380.     control:            ControlHandle;
  3381.     theRect:         Rect;
  3382.  
  3383. BEGIN
  3384.     PenNormal;
  3385.     LUpdate(window^.VisRgn, SndDocPeek(window)^.list);        {update list}
  3386.     theRect:= SndDocPeek(window)^.list^^.rView;                {frame the list}
  3387.     theRect.right:= theRect.right + kScrollBarAdjust;
  3388.     InsetRect(theRect, kListFrameInset, kListFrameInset);
  3389.     FrameRect(theRect);
  3390.     UpdtControl(window, window^.visRgn);                        {update controls}
  3391.     control:= WindowPeek(window)^.controlList;                {draw button outline}
  3392.     WHILE control <> NIL DO BEGIN
  3393.         IF GetCRefCon(control) = rPlaySndCntl THEN
  3394.             DoButtonOutline(control);
  3395.         control:= control^^.nextControl;
  3396.     END;
  3397. END; {DrawWindow}
  3398.  
  3399. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3400. {$S Main}
  3401. PROCEDURE DoKeyDown(key: CHAR; window: WindowPtr);
  3402.  
  3403. {When the user types a key, I check if it is one that I’m looking for.
  3404.  This routine only handles the non-command key events.  Here I’m looking
  3405.  for a arrow key or the return and enter keys for the default button.
  3406.  
  3407.  VERSION 1.1: The enter and return keys only work if there is a selection.
  3408.  Now supporting the backspace and delete keys which clear the selection.}
  3409.  
  3410. VAR
  3411.     control:            ControlHandle;
  3412.     ignore:            BOOLEAN;
  3413.     kind:                INTEGER;
  3414.     r:                    Rect;
  3415.  
  3416. BEGIN
  3417.     CASE GetWRefCon(window) OF
  3418.  
  3419.         rSoundWindow: BEGIN
  3420.             CASE key OF
  3421.  
  3422.                 kEnterKey, kReturnKey: BEGIN
  3423.                     IF HasSelection(SndDocPeek(window)) THEN BEGIN
  3424.                         control:= WindowPeek(window)^.controlList;
  3425.                         WHILE control <> NIL DO BEGIN            {find the default button}
  3426.                             IF GetCRefCon(control) = rPlaySndCntl THEN
  3427.                                 SelectButton(control);            {here it is}
  3428.                             control:= control^^.nextControl;
  3429.                         END;
  3430.                         PlaySelectedSnd(SndDocPeek(window), sPlayingMsg);
  3431.                     END;
  3432.                 END;
  3433.  
  3434.                 kUpArrow: BEGIN
  3435.                     SelectNextCell(SndDocPeek(window)^.list, FALSE);
  3436.                     ActivateSndCntls(SndDocPeek(window));
  3437.                 END;
  3438.  
  3439.                 kDownArrow: BEGIN
  3440.                     SelectNextCell(SndDocPeek(window)^.list, TRUE);
  3441.                     ActivateSndCntls(SndDocPeek(window));
  3442.                 END;
  3443.                 
  3444.                 kBackspace, kDelete:
  3445.                     ClearSnd(SndDocPeek(window));
  3446.             END;
  3447.         END; {rSoundWindow}
  3448.  
  3449.         rStatusWindow:
  3450.             IF key IN [kEnterKey, kReturnKey, kEscape] THEN BEGIN
  3451.                 SelectButton(WindowPeek(window)^.controlList);
  3452.                 KillSound;
  3453.             END;
  3454.  
  3455.         rAboutWindow:
  3456.             IF key IN [kEnterKey, kReturnKey, kEscape] THEN BEGIN
  3457.                 SelectButton(WindowPeek(window)^.controlList);
  3458.                 ignore:= DoCloseWindow(window);
  3459.             END;
  3460.         END; {CASE GetWRefCon(window)}
  3461. END; {DoKeyDown}
  3462.  
  3463. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3464. {$S Main}
  3465. FUNCTION ListClick(sndDoc: SndDocPeek; event: EventRecord): BOOLEAN;
  3466.  
  3467. {Given a document, this will handle any clicking in the list.  The mouse
  3468.  point (event.where) is expected to have been adjusted to the local
  3469.  coordinates of the window.  If this routine does handle the event, then
  3470.  I return TRUE.
  3471.  
  3472.  BUG NOTE: LClick will return a double-click even if no cell was selected.
  3473.  So I have to test for the last click being in a real cell.  If not, then
  3474.  I will not process the double click.  Also, there is another bug in the
  3475.  List Manager.  It will not always deselect the currently selected cell when
  3476.  the user clicks outside of the data bounds.  In other words, sometimes
  3477.  my list would show 4 items when the list has room to show 8.  If the user
  3478.  clicked in the bottom area of the list (below the last item) the List
  3479.  Manager should deselect any items.  It doesn’t all the time, just sometimes.
  3480.  The only real solution would be to write a new LClick.}
  3481.  
  3482. VAR
  3483.     aCell:            Cell;
  3484.     listRect:        Rect;
  3485.  
  3486. BEGIN
  3487.     listRect:= sndDoc^.list^^.rView;
  3488.     listRect.right:= listRect.right + kScrollBarAdjust;
  3489.     IF PtInRect(event.where, listRect) THEN BEGIN
  3490.         IF LClick(event.where, event.modifiers, sndDoc^.list) THEN BEGIN
  3491.             aCell:= LLastClick(sndDoc^.list);
  3492.             IF PtInRect(aCell, sndDoc^.list^^.dataBounds) THEN
  3493.                 PlaySelectedSnd(sndDoc, sPlayingMsg);
  3494.         END;
  3495.         ActivateSndCntls(sndDoc);
  3496.         ListClick:= TRUE;                                            {I handled the event}
  3497.     END ELSE
  3498.         ListClick:= FALSE;
  3499. END;
  3500.  
  3501. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3502. {$S Main}
  3503. PROCEDURE DoSndDocClick(sndDoc: SndDocPeek; event: EventRecord);
  3504.  
  3505. {This is called when a mouse-down event occurs in the content of my
  3506.  application windows.  First thing to check for is a click in the list.
  3507.  If not a list click, then find what control may have been clicked in and
  3508.  handle that.
  3509.  
  3510.  VERSION 1.1: Handle the record button.}
  3511.  
  3512. VAR
  3513.     control:         ControlHandle;
  3514.  
  3515. BEGIN
  3516.     SetPort(GrafPtr(sndDoc));
  3517.     GlobalToLocal(event.where);
  3518.     IF NOT ListClick(sndDoc, event) THEN BEGIN
  3519.         IF FindControl(event.where, WindowPtr(sndDoc), control) <> 0 THEN BEGIN
  3520.             IF TrackControl(control, event.where, NIL) <> 0 THEN BEGIN
  3521.                 CASE GetCRefCon(control) OF
  3522.  
  3523.                     rPlaySndCntl:
  3524.                         PlaySelectedSnd(sndDoc, sPlayingMsg);
  3525.  
  3526.                     rHyperPlayCntl:
  3527.                         PlaySelectedSnd(sndDoc, sHyperMsg);
  3528.  
  3529.                     rPlayScaleCntl:
  3530.                         PlaySndSong(sndDoc, rScaleSnd);
  3531.  
  3532.                     rMelodyCntl:
  3533.                         PlaySndSong(sndDoc, rMelodyPart1);
  3534.  
  3535.                     rStopCntl:
  3536.                         KillSound;
  3537.  
  3538.                     rRecordCntl:
  3539.                         DoRecordSound(sndDoc);
  3540.  
  3541.                 END; {CASE GetCRefCon(control)}
  3542.             END; {IF TrackControl}
  3543.         END; {IF FindControl}
  3544.     END; {IF NOT ListSelect}
  3545. END; {DoSndDocClick}
  3546.  
  3547. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3548. {$S Main}
  3549. PROCEDURE DoStatClick(statWindow: StatWindowPeek; event: EventRecord);
  3550.  
  3551. {The status window has a stop button.  This will stop any sound in
  3552.  progress.  So, if the user clicks in my status window I need to check
  3553.  for this.}
  3554.  
  3555. VAR
  3556.     control:         ControlHandle;
  3557.  
  3558. BEGIN
  3559.     SetPort(GrafPtr(statWindow));
  3560.     GlobalToLocal(event.where);
  3561.     IF FindControl(event.where, WindowPtr(statWindow), control) <> 0 THEN
  3562.         IF TrackControl(control, event.where, NIL) <> 0 THEN
  3563.             KillSound;
  3564. END;
  3565.  
  3566. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3567. {$S Main}
  3568. PROCEDURE DoAboutClick(window: WindowPtr; event: EventRecord);
  3569.  
  3570. {The about window has a single OK button.  If the users clicks in it, then
  3571.  close the window.}
  3572.  
  3573. VAR
  3574.     control:         ControlHandle;
  3575.     ignore:            BOOLEAN;
  3576.  
  3577. BEGIN
  3578.     SetPort(window);
  3579.     GlobalToLocal(event.where);
  3580.     IF FindControl(event.where, WindowPtr(window), control) <> 0 THEN BEGIN
  3581.         IF TrackControl(control, event.where, NIL) <> 0 THEN
  3582.             ignore:= DoCloseWindow(window);
  3583.     END;
  3584. END;
  3585.  
  3586. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3587. {$S Main}
  3588. PROCEDURE DoUpdate(window: WindowPtr);
  3589.  
  3590. {This is called when an update event is received for any of my windows.  It
  3591.  calls the appropriate window’s update routine to draw its contents.  As an
  3592.  efficiency measure that does not have to be followed, it calls the drawing
  3593.  routine only if the visRgn is non-empty.  This will handle situations
  3594.  where calculations for drawing or drawing itself is very time-consuming.
  3595.  Why does QD give you an update with an empty updateRgn?}
  3596.  
  3597. BEGIN
  3598.     BeginUpdate(window);                                {setup the visRgn, clears updateRgn}
  3599.     IF NOT EmptyRgn(window^.visRgn) THEN BEGIN     {if updating to be done}
  3600.         SetPort(window);                                {set to the current port}
  3601.         CASE GetWRefCon(window) OF                    {call the window’s drawing routine}
  3602.  
  3603.             rSoundWindow:
  3604.                 DrawSndWindow(window);
  3605.  
  3606.             rStatusWindow:
  3607.                 DrawStatusWindow;
  3608.  
  3609.             rAboutWindow:
  3610.                 DrawAboutWindow(window);
  3611.         END;
  3612.     END;
  3613.     EndUpdate(window);                                {restores the visRgn}
  3614. END; {DoUpdate}
  3615.  
  3616. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3617. {$S Main}
  3618. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  3619.  
  3620. {This is called when a window is to be activated or deactivated.  For the
  3621.  document window I activate all the controls and the list.  For the status
  3622.  window I activate the one and only control.  This is also called for
  3623.  suspend and resume events while running MultiFinder.}
  3624.  
  3625. VAR
  3626.     kind:            INTEGER;
  3627.     button:        ControlHandle;
  3628.     r:                Rect;
  3629.  
  3630. BEGIN
  3631.     IF window <> NIL THEN BEGIN
  3632.         CASE GetWRefCon(window) OF
  3633.  
  3634.             rSoundWindow: BEGIN
  3635.                 ActivateSndCntls(SndDocPeek(window));
  3636.                 LActivate(becomingActive, SndDocPeek(window)^.list);
  3637.             END;
  3638.  
  3639.             rStatusWindow: BEGIN
  3640.                 IF becomingActive THEN                            {it only has one control}
  3641.                     HiliteControl(WindowPeek(window)^.controlList, kCntlActivate)
  3642.                 ELSE
  3643.                     HiliteControl(WindowPeek(window)^.controlList, kCntlDeactivate);
  3644.                 DoButtonOutline(WindowPeek(window)^.controlList);
  3645.             END;
  3646.  
  3647.             rAboutWindow: BEGIN
  3648.                 IF becomingActive THEN                            {it only has one control}
  3649.                     HiliteControl(WindowPeek(window)^.controlList, kCntlActivate)
  3650.                 ELSE
  3651.                     HiliteControl(WindowPeek(window)^.controlList, kCntlDeactivate);
  3652.                 DoButtonOutline(WindowPeek(window)^.controlList);
  3653.             END;
  3654.  
  3655.         END;
  3656.     END;
  3657. END; {DoActivate}
  3658.  
  3659. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3660. {$S Main}
  3661. PROCEDURE DoEvent(event: EventRecord);
  3662.  
  3663. {As Spike Lee says, “Do the right thing.” Determine what kind of event it
  3664.  is, and call the appropriate routines.  Key down events are first tested
  3665.  as being command key events for menus or command-. for cancel.  If it’s
  3666.  the command-. the user is asking to cancel the sound.  In this case, if
  3667.  the front window is the status window then the button should look as if it
  3668.  has been clicked.  This is proper human interface.  Any non-menu command
  3669.  keys are passed to DoKeyDown.  I have a global flag, gInModalState, which
  3670.  is used to handle the front window as a modal dialog.  This means I ignore
  3671.  clicks outside of the modal window and menu command keys.  I could have a
  3672.  different global flag that would mean it’s a modal window but uses menu
  3673.  commands, such as gInModalMenuState.  An important note is that I do pass
  3674.  any other non-menu command keys to DoKeys, so the modal window could have
  3675.  access to key events.  One last thing to note happens during a suspend
  3676.  event.   Applications using sound should dispose of their sound channels
  3677.  at suspend time.  No other application can use sound while another one has
  3678.  channels allocated.  To stop my sound, I call KillSound which hides the
  3679.  status window.  MultiFinder does properly deactivate the front window at
  3680.  suspend time and applications normally do not have to worry about
  3681.  HiliteWindow.  I do because the front window could have been the status
  3682.  window and I’ve removed it after getting a suspend event.  This causes the
  3683.  next window, a document window, to become highlighted as the active
  3684.  window.  To avoid my next window from being highlighted while in the
  3685.  background, I have to call HiliteWindow *after* KillSound.  This is
  3686.  strange and only applications changing the front window at suspend event
  3687.  time have to be concerned about this.
  3688.  
  3689.  VERSION 1.1: Added a constant, kSFTopLeft, to specify the dialog position.
  3690.  I do not call KillSound during a MultiFinder switch unless we're running
  3691.  the older Sound Manager.  The new one allows for multiple sound
  3692.  channels or will return the proper error otherwise.}
  3693.  
  3694. CONST
  3695. {OSEvent is the event number of the suspend/resume and mouse-moved events
  3696.  sent by MultiFinder.  Once I determine an osEvent has occurred, I look at
  3697.  the high byte of the message sent to determine which kind it is.  To
  3698.  further differentiate suspend and resume events, it is necessary to check
  3699.  the low bit of the message.  I’m using the more efficient MPW bit
  3700.  routines.}
  3701.  
  3702. {    osEvt =            app4Evt;        defined in post MPW 3.0 Events.p}
  3703. {    suspendResumeMessage = 1;    defined in post MPW 3.0 Events.p}
  3704.     kGetHighByte =    24;            {24 bits (three bytes) to shift right}
  3705.     kResumeMask =    1;                {resume event is a 1 in low bit of message}
  3706.  
  3707. VAR
  3708.     window:            WindowPtr;
  3709.     finalTicks:        LongInt;
  3710.     part, err:        INTEGER;
  3711.     ignore:            BOOLEAN;
  3712.     key:                CHAR;
  3713.  
  3714. BEGIN
  3715.     CASE event.what OF
  3716.         mouseDown: BEGIN
  3717.             part:= FindWindow(event.where, window);
  3718.             IF (IsModalWindow(FrontWindow) & (window <> FrontWindow))
  3719.              | (IsModalWindow(FrontWindow) & (part = inMenuBar)) THEN BEGIN
  3720.                 DoErrorSound(1);                            {click outside of modal window}
  3721.                 EXIT(DoEvent);                                {break out of routine}
  3722.             END;
  3723.             CASE part OF
  3724.                 inMenuBar: BEGIN                            {process the menu command}
  3725.                     AdjustMenus;
  3726.                     DoMenuCommand(MenuSelect(event.where));
  3727.                 END;
  3728.  
  3729.                 inSysWindow:                                {let system handle the mouseDown}
  3730.                     SystemClick(event, window);
  3731.  
  3732.                 inContent: BEGIN
  3733.                     IF (window <> FrontWindow) THEN
  3734.                         SelectWindow(window)
  3735.                     ELSE BEGIN
  3736.                         CASE GetWRefCon(window) OF
  3737.  
  3738.                             rSoundWindow:
  3739.                                 DoSndDocClick(SndDocPeek(window), event);
  3740.  
  3741.                             rStatusWindow:
  3742.                                 DoStatClick(StatWindowPeek(window), event);
  3743.  
  3744.                             rAboutWindow:
  3745.                                 DoAboutClick(window, event);
  3746.  
  3747.                             END; {CASE GetWRefCon(window)}
  3748.                         END;
  3749.                     END; {inContent}
  3750.  
  3751.                 inDrag:                        {pass screenBits.bounds to get all gDevices}
  3752.                     DragWindow(window, event.where, screenBits.bounds);
  3753.  
  3754.                 inGoAway: BEGIN
  3755.                     IF TrackGoAway(window, event.where) THEN
  3756.                         ignore:= DoCloseWindow(window);
  3757.                     END;
  3758.  
  3759.             END; {CASE}
  3760.         END; {mouseDown}
  3761.  
  3762.         keyDown, autoKey: BEGIN
  3763.             window:= FrontWindow;
  3764.             key:= CHR(BAnd(event.message, charCodeMask));
  3765.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN BEGIN    {Command key down}
  3766.                 IF key = kPeriod THEN BEGIN
  3767.                     IF window = WindowPtr(gStatusWindow) THEN
  3768.                         SelectButton(WindowPeek(gStatusWindow)^.controlList);
  3769.                     KillSound;
  3770.                 END ELSE
  3771.                     IF (event.what = keyDown) & (NOT IsModalWindow(window)) THEN BEGIN
  3772.                         AdjustMenus;    {enable/disable/check menu items properly}
  3773.                         DoMenuCommand(MenuKey(key));
  3774.                     END;
  3775.             END ELSE                                                            {non-Command keys}
  3776.                 IF window <> NIL THEN                                    {if there’s a window}
  3777.                     DoKeyDown(key, window);
  3778.         END;
  3779.  
  3780.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  3781.             DoActivate(WindowPtr(event.message),
  3782.                             BAnd(event.modifiers, activeFlag) <> 0);
  3783.  
  3784.         updateEvt:                            {call DoUpdate with the window to update}
  3785.             DoUpdate(WindowPtr(event.message));
  3786.  
  3787.         diskEvt:                                {Call DIBadMount in response to a diskEvt}
  3788.             IF HiWrd(event.message) <> noErr THEN BEGIN
  3789.                 err:= DIBadMount(Point(kSFTopLeft), event.message);
  3790.             END;
  3791.  
  3792.         osEvt: BEGIN
  3793.             CASE BSR(event.message, kGetHighByte) OF    {high byte of message}
  3794.  
  3795.                 suspendResumeMessage: BEGIN
  3796.                     IF BAnd(event.message, kResumeMask) <> 0 THEN
  3797.                         gInBackground:= FALSE                {it was a resume event}
  3798.                     ELSE BEGIN
  3799.                         gInBackground:= TRUE;                {it was a suspend event}
  3800.                         IF NOT HasNewSndMgr THEN
  3801.                             KillSound;                            {stop any sound}
  3802.                         window:= FrontWindow;                {get front window}
  3803.                         IF window <> NIL THEN                 {don’t use a NIL window}
  3804.                             HiliteWindow(window, FALSE);    {then properly activate it}
  3805.                     END;
  3806.                     DoActivate(FrontWindow, NOT gInBackground);
  3807.                 END; {suspendResumeMessage}
  3808.  
  3809.             END; {CASE}
  3810.         END; {osEvt}
  3811.  
  3812.     END; {CASE event.what}
  3813. END; {DoEvent}
  3814.  
  3815. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3816. {$S Main}
  3817. PROCEDURE AdjustCursor(region: RgnHandle);
  3818.  
  3819. {Change the cursor’s shape, depending on its current position.  This also
  3820.  calculates the region where the current cursor resides (for
  3821.  WaitNextEvent).  This is based on its current position in global
  3822.  coordinates.  If the mouse is ever outside of that region, an event is
  3823.  generated causing this routine to be called again by the event loop.  This
  3824.  allows me to change the region to where the mouse is currently located.
  3825.  If there is more to the event than just “the mouse moved,” this gets
  3826.  called before the event is processed to make sure the cursor is the right
  3827.  one.  In any (ahem) event, this is called again before I fall back into
  3828.  WaitNextEvent.  Extreme integer values are used to create a wide open
  3829.  region.  -MAXINT - 1 is the largest negative integer (-32768) and MAXINT
  3830.  is the largest positive integer (32767).
  3831.  
  3832.  BUG NOTE: The largest positive value for a region’s size is MAXINT - 1
  3833.  due to a very old bug that still remains to this day.}
  3834.  
  3835. VAR
  3836.     window:                 WindowPtr;
  3837.     arrowRgn,
  3838.     sndCursorRgn:        RgnHandle;
  3839.     sndCursorRect:        Rect;
  3840.  
  3841. BEGIN
  3842.     window:= FrontWindow;        {I only adjust the cursor when I am in front}
  3843.     IF (NOT gInBackground) & (NOT IsDAWindow(window)) THEN BEGIN
  3844.  
  3845.         arrowRgn:= NewRgn;        {calculate regions for different cursor shapes}
  3846.         sndCursorRgn:= NewRgn;    {start with a big, big rectangular region}
  3847.         SetRectRgn(arrowRgn, -MAXINT - 1, -MAXINT - 1, MAXINT - 1, MAXINT - 1);
  3848.  
  3849.         IF IsDocWindow(window) THEN BEGIN    {calculate region for document cursor}
  3850.             sndCursorRect:= window^.portRect;
  3851.             SetPort(window);
  3852.             WITH sndCursorRect DO BEGIN        {make a global version of the viewRect}
  3853.                 LocalToGlobal(topLeft);
  3854.                 LocalToGlobal(botRight);
  3855.             END;
  3856.             RectRgn(sndCursorRgn, sndCursorRect);
  3857.             WITH window^.portBits.bounds DO
  3858.                 SetOrigin(-left, -top);
  3859.             SectRgn(sndCursorRgn, window^.visRgn, sndCursorRgn);
  3860.             SetOrigin(0, 0);
  3861.         END;
  3862.  
  3863.         DiffRgn(arrowRgn, sndCursorRgn, arrowRgn);    {subtract other region}
  3864.         IF PtInRgn(GetGlobalMouse, sndCursorRgn) THEN BEGIN
  3865.             SetCursor(GetCursor(rSndCursor)^^);         {change cursor and region}
  3866.             CopyRgn(sndCursorRgn, region);
  3867.         END ELSE BEGIN
  3868.             SetCursor(arrow);
  3869.             CopyRgn(arrowRgn, region);
  3870.         END;
  3871.         DisposeRgn(arrowRgn);                {get rid of our local regions}
  3872.         DisposeRgn(sndCursorRgn);
  3873.     END;
  3874. END; {AdjustCursor}
  3875.  
  3876. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3877. {$S Main}
  3878. PROCEDURE EventLoop;
  3879.  
  3880. {Get events forever, and handle them by calling DoEvent.  Since this
  3881.  application requires System 6.0x or later I know that _WaitNextEvent is
  3882.  always there, even without MultiFinder.  MultiFinder’s sleep is used to
  3883.  determine how often I want to receive events, regardless if an event has
  3884.  actually occurred.  In this application, I don’t perform any background
  3885.  processing so I’m being super friendly by using MAXLONGINT as a sleep
  3886.  value.  This also helps keep Virtual Memory from paging me in just to run
  3887.  my event loop and find out that nothing happened.  The application will
  3888.  only be called upon for events that must be handled.  Also call
  3889.  AdjustCursor each time through the loop.  AdjustCursor will return the
  3890.  current region containing the mouse and is passed to WaitNextEvent.  If
  3891.  the mouse travels out of the region, another event is generated.  I have
  3892.  to call AdjustCursor just before doing the event to make sure the right
  3893.  cursor is shown.  Another thing, if I have a sound playing asynchronously
  3894.  then I want to dispose of my channel as soon as possible.  I set up a flag
  3895.  in the SoundUnit that will keep track of when it has a channel allocated.
  3896.  I can call the SndChanOpen function to find out if this is true.  It
  3897.  pretty much like keeping track of when you’re in the background.  If a
  3898.  channel is open, then the MultiFinder sleep time is adjusted to a
  3899.  reasonable time that will allow me to catch when the sound has completed
  3900.  so that I may dispose of my channels and status window.  That’s when I
  3901.  return kPollingSleepTime.
  3902.  
  3903.  VERSION 1.1: No longer putting the SANELib into a seperate unit, which then
  3904.  needed to be unloaded.  Instead, I merge it into the Main segment.  Refer
  3905.  to the Make file for further information.}
  3906.  
  3907.  
  3908. VAR
  3909.     cursorRgn:             RgnHandle;
  3910.     event:                 EventRecord;
  3911.     sleep:                LONGINT;
  3912.  
  3913. BEGIN
  3914.     cursorRgn:= NewRgn;                        {1st time pass WNE an empty region}
  3915.     REPEAT
  3916.         IF SndChanOpen THEN                                    {if we’re playing a sound}
  3917.             sleep:= kPollingSleepTime                        {use the polling sleep value}
  3918.         ELSE BEGIN
  3919.             sleep:= MAXLONGINT;                                {default value for sleep}
  3920.             UnloadSeg(@_SoundUnit);                            {unload the Sound Unit}
  3921.         END;
  3922.         UnloadSeg(@OpenSoundDoc);                            {unload the open code}
  3923.         IF SoundCompletion THEN
  3924.             KillSound;
  3925.         IF LowOnReserve THEN
  3926.             RecoverReserve;
  3927.         AdjustCursor(cursorRgn);                            {get the right cursor}
  3928.         IF WaitNextEvent(everyEvent, event, sleep, cursorRgn) THEN BEGIN
  3929.             AdjustCursor(cursorRgn);                        {get the right cursor}
  3930.             DoEvent(event);
  3931.         END;
  3932.     UNTIL FALSE;                    {loop forever; I quit through Terminate}
  3933. END; {EventLoop}
  3934.  
  3935.  
  3936. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  3937. {$S Initialization}
  3938. PROCEDURE Initialize;
  3939.  
  3940. {Set up the whole world.  Initialize global variables, Toolbox managers,
  3941.  and menus.  If a failure occurs here, I will consider that the application
  3942.  is in such bad shape that I should just exit.  Your error handling may
  3943.  differ, but the checks should still be made.  I ask for a set of master
  3944.  pointer blocks and all permanent storage at this point to cut down on
  3945.  memory fragmentation.  I may be opening large numbers of resources and
  3946.  documents so I allocate some extra master pointer blocks at the start.
  3947.  
  3948.  VERSION 1.1:  Now supports opening of documents from the Finder.}
  3949.  
  3950. CONST
  3951.     kBroughtToFront =    3;
  3952.  
  3953. VAR
  3954.     event:                 EventRecord;
  3955.     menuBar:             Handle;
  3956.     total, contig:        LONGINT;
  3957.     ignoreError:        OSErr;
  3958.     ignoreResult:         BOOLEAN;
  3959.     theFile:                AppFile;
  3960.     message, count,
  3961.     index:                INTEGER;
  3962.     
  3963. BEGIN
  3964.     gInBackground:= FALSE;                        {we’ll be in the foreground soon}
  3965.     gAppResRef:= CurResFile;                    {save the resRef to myself}
  3966.     FOR count:= 1 TO kNumberOfMasters DO    {allocate master pointer blocks}
  3967.         MoreMasters;
  3968.     InitGraf(@thePort);                            {init managers, yawn...}
  3969.     InitFonts;
  3970.     InitWindows;
  3971.     InitMenus;
  3972.     TEInit;
  3973.     InitDialogs(NIL);
  3974.     InitCursor;
  3975.  
  3976. {This next line prevents the Dialog Manager from calling _SysBeep.
  3977.  If I get a memory or resource Manager error it wouldn’t be the best
  3978.  of plans to call  _SysBeep which will want to allocate memory and load
  3979.  a few resources.  Which could be bad if I just gave an Alert signalling
  3980.  an out of memory condition.}
  3981.  
  3982.     ErrorSound(@DoErrorSound);
  3983.  
  3984. {This code is necessary to pull the application into the foreground.  I use
  3985.  EventAvail because I don’t want to remove any events the user may have
  3986.  done, such as typing ahead.  Until the application has made a few calls (3
  3987.  seems to be the magic number) to the Event Manager, MultiFinder keeps me
  3988.  in the background.   Splashscreens and Alerts will remain in a background
  3989.  layer until we get a few events.  This is documented in Tech Note #180.}
  3990.  
  3991.     FOR count:= 1 TO kBroughtToFront DO
  3992.         ignoreResult:= EventAvail(everyEvent, event);
  3993.  
  3994. {Ignore the error returned from SysEnvirons; even if an error occurred,
  3995.  the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  3996.  call to SysEnvirons by calling it after initializing AppleTalk.}
  3997.  
  3998.     ignoreError:= SysEnvirons(kSysEnvironsVersion, gMac);
  3999.  
  4000. {Make sure we’re running the right system.  If the Sound Manager is not
  4001.  available, then there’s no point in continuing.}
  4002.  
  4003.     IF gMac.systemVersion < kSystem602 THEN
  4004.         EmergencyExit(sWrongVersion);
  4005.  
  4006. {Call the SoundUnit to initialize itslef.  If the unit encounters an error,
  4007.  then it cannot be used and this means I’m leaving too.}
  4008.  
  4009.     IF InitSoundUnit <> noErr THEN                {allocates 4 * 1064 bytes}
  4010.         EmergencyExit(sInitSoundErr);
  4011.  
  4012. {Before I go any further, I want my reserve memory.  This is an emergency
  4013.  reserve (sorta like my old VW had) when memory runs low.  If I cannot
  4014.  obtain this reserve, then I’ll bail.  It’s also important to obtain my
  4015.  reserve before testing if I have the desired amount of memory to run
  4016.  this application.  Also, FailLowMemory will consider the memory reserve.}
  4017.  
  4018.     IF NOT AllocateReserve THEN
  4019.         EmergencyExit(sLowMemory);
  4020.     SetGrowZone(@MyGrowZone);
  4021.     
  4022.     menuBar:= GetNewMBar(rMenuBar);                {read menus into menu bar}
  4023.     IF menuBar = NIL THEN
  4024.         EmergencyExit(sNoMenus);                    {wow, how’d that happen?}
  4025.     SetMenuBar(menuBar);                                {install menus}
  4026.     DisposHandle(menuBar);
  4027.     AddResMenu(GetMHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  4028.     DrawMenuBar;
  4029.  
  4030.     InitStatusWindow;                                    {get the status window ready}
  4031.     InitCursorCtl(NIL);                                {MPW’s handy cursor routines}
  4032.  
  4033. {Last, I want to make sure that enough memory is free for my application to
  4034.  run.  It is possible that user may have adjusted the SIZE resource to too
  4035.  small a setting or for some other reason the application started up in a
  4036.  very small memory partition.  It’s also possible for a situation to arise
  4037.  where the heap may have been of the requested size taken from the SIZE
  4038.  resource, but a large scrap was loaded which left too little memory.  I
  4039.  want to make sure that my free memory is not being modified by the scrap’s
  4040.  presence.  So, I unload it to disk but if the application will run once
  4041.  the scrap is unloaded, then you’ll probably not get it back into memory.
  4042.  Thus losing the clipboard contents.  I preform this check after
  4043.  initializing all the Toolbox and the basic features of this application,
  4044.  such as showing the about box.}
  4045.  
  4046.     IF FailLowMemory(kMinSpace) THEN BEGIN
  4047.         IF UnloadScrap <> noErr THEN
  4048.             EmergencyExit(sLowMemory)
  4049.         ELSE BEGIN
  4050.             IF FailLowMemory(kMinSpace) THEN
  4051.                 EmergencyExit(sLowMemory);
  4052.         END;
  4053.     END;
  4054.  
  4055. {I check the sound volume after testing for a minimal amount of memory to
  4056.  run.  Otherwise I might end up telling the user to adjust the volume and
  4057.  the quitting because memory was too low.}
  4058.  
  4059.     CheckSndVol;                                        {check the sound volume level}
  4060.     
  4061.     CountAppFiles(message, count);                {any files to open?}
  4062.     FOR index:= 1 TO count DO BEGIN                {go get 'em}
  4063.         GetAppFiles(index, theFile);
  4064.         OpenSoundDoc(@theFile.fName, theFile.vRefNum);
  4065.     END;
  4066.     ClrAppFiles(count);
  4067. END; {Initialize}
  4068.  
  4069. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  4070. PROCEDURE _DataInit; EXTERNAL;
  4071.  
  4072. {This routine is contained in the MPW runtime library.  It will be placed
  4073.  into the code segment used to initialize the A5 globals.  This external
  4074.  reference to it is done so that we can unload that segment, named %A5Init.}
  4075.  
  4076. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  4077. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN PROGRAM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  4078. {$S Main}
  4079. BEGIN
  4080.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  4081.  
  4082. {If you have stack requirements that differ from the default, then you
  4083.  could use SetApplLimit to increase StackSpace at this point, before
  4084.  calling MaxApplZone.}
  4085.  
  4086.     MaxApplZone;                {expand the heap so code segments load at the top}
  4087.     Initialize;                    {initialize the program}
  4088.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  4089.     EventLoop;                    {call the main event loop}
  4090. END.
  4091. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN PROGRAM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  4092. {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
  4093.